Order rows with specific parameters
I have this table filled as follows http://sqlfiddle.com/#!2/3736a/4, what
I'm trying to do is the next:
I have n groups of names (in this case 4 group names: CAFE NESCAFE, CAFE
LEGAL, CAFE INTERNA, null) from the column nom_agrupacion, and I need to
sort them first by nom_agrupacion (name of group) and then by other column
which is costo.
The query to do that is this
SELECT * FROM bby_venta_co WHERE promocion_id = 100000189
AND ti = 153
AND ffi = 12
AND ci = 1
ORDER BY nom_agrupacion DESC, costo DESC;
and get this
ID DTTI TI FFI CI PROMOCION_ID CODIGO_BARRAS COSTO
NOM_AGRUPACION
53 1101 153 12 1 100000189 7501001602727 34.55 CAFE
NESCAFE
55 1102 153 12 1 100000189 7501001602727 34.55 CAFE
NESCAFE
62 1107 153 12 1 100000189 7501059224841 19.45 CAFE
NESCAFE
65 1108 153 12 1 100000189 17501052411115 28.3 CAFE
LEGAL
66 1109 153 12 1 100000189 17501052411115 28.3 CAFE
LEGAL
67 1110 153 12 1 100000189 7501052411118 24.8 CAFE
LEGAL
57 1103 153 12 1 100000189 7501052411118 24.8 CAFE
LEGAL
61 1106 153 12 1 100000189 17501052418732 55.6 CAFE
INTERNA
52 1100 153 12 1 100000189 27501052418739 32.6 CAFE
INTERNA
51 1099 153 12 1 100000189 27501052418739 32.6 CAFE
INTERNA
60 1105 153 12 1 100000189 7501052418520 19.35 CAFE
INTERNA
59 1104 153 12 1 100000189 7501000112388 12.9 (null)
68 1111 153 12 1 100000189 7501000112388 12.9 (null)
But I need to sort the information so I can get this: Bring the first row
of every group name(I got 4 becasue null counts as group also) then bring
the second row of every group and so on to get something like this
ID DTTI TI FFI CI PROMOCION_ID CODIGO_BARRAS COSTO
NOM_AGRUPACION
53 1101 153 12 1 100000189 7501001602727 34.55 CAFE
NESCAFE
66 1109 153 12 1 100000189 17501052411115 28.3 CAFE
LEGAL
61 1106 153 12 1 100000189 17501052418732 55.6 CAFE
INTERNA
59 1104 153 12 1 100000189 7501000112388 12.9 (null)
55 1102 153 12 1 100000189 7501001602727 34.55 CAFE
NESCAFE
65 1108 153 12 1 100000189 17501052411115 28.3 CAFE
LEGAL
52 1100 153 12 1 100000189 27501052418739 32.6 CAFE
INTERNA
68 1111 153 12 1 100000189 7501000112388 12.9 (null)
62 1107 153 12 1 100000189 7501059224841 19.45 CAFE
NESCAFE
57 1103 153 12 1 100000189 7501052411118 24.8 CAFE
LEGAL
51 1099 153 12 1 100000189 27501052418739 32.6 CAFE
INTERNA
60 1105 153 12 1 100000189 7501052418520 19.35 CAFE
INTERNA
Is this even possible in one query?
I have tried to at least bring the first row of every group once but my
query isn't working properly:
SELECT * FROM bby_venta_co WHERE promocion_id = 100000189
AND ti = 153
AND ffi = 12
AND ci = 1
GROUP BY costo, nom_agrupacion
ORDER BY nom_agrupacion DESC, costo DESC;
I use group by to first bring the single cost and then bring the single
nom_agrupacion but it seems it only reads cost, and if I only use group by
nom_agrupacion it doesn't bring me the rows of column costo with the
highest values.
Any help will be appreciate.
No comments:
Post a Comment