使用GROUP BY和条件ORDER BY

时间:2014-01-02 16:09:04

标签: mysql sql group-by sql-order-by

我遇到查询问题,使用“group by”和条件“订单”来获取正确的数据。 以下是没有“group by”

的查询
SELECT gc.GES_PERSONAL_ID AS pid, gc.FPVAL AS fpval, gc.FECHA_HORA AS fh, gc.ENTRADA_SALIDA AS es
FROM ges_capturador AS gc
WHERE (gc.FPVAL >= '2013-12-25' AND gc.FPVAL <= '2013-12-26')
AND gc.GES_PERSONAL_ID=138
AND gc.GES_BANDERA_ID=1
AND gc.ESTADO=true
AND (gc.ENTRADA_SALIDA=1 OR gc.ENTRADA_SALIDA=0)
ORDER BY gc.FPVAL, CASE gc.ENTRADA_SALIDA WHEN 1 THEN gc.FH END ASC, CASE WHEN gc.ENTRADA_SALIDA = 0 THEN gc.FH END DESC

通过该查询,我可以获得这些天的所有数据,并按照我的要求进行排序。如果ENTRADA_SALIDA = 1,那么fh字段的排序是ASC,当为0时,sort是DESC。

+------+------------+---------------------+------+
| pid  | fpval      | fh                  | es   |
+------+------------+---------------------+------+
|  138 | 2013-12-25 | 2013-12-26 01:06:16 |    0 |
|  138 | 2013-12-25 | 2013-12-26 01:05:40 |    0 |
|  138 | 2013-12-25 | 2013-12-25 14:29:00 |    0 |
|  138 | 2013-12-25 | 2013-12-25 14:28:20 |    1 |
|  138 | 2013-12-25 | 2013-12-25 14:29:11 |    1 |
+------+------------+---------------------+------+

嗯,问题是我想要每个案例的第一个寄存器(ENTRADA_SALIDA =&gt; 0和1)。但是,这是添加“group by”的查询,以删除我在结果中不需要的寄存器:

SELECT gc.GES_PERSONAL_ID AS pid, gc.FPVAL AS fpval, gc.FECHA_HORA AS fh, gc.ENTRADA_SALIDA AS es
FROM ges_capturador AS gc
WHERE (gc.FPVAL>='2013-12-25' AND gc.FPVAL<='2013-12-26')
AND gc.GES_PERSONAL_ID=138
AND gc.GES_BANDERA_ID=1
AND gc.ESTADO=true
AND (gc.ENTRADA_SALIDA=1 OR gc.ENTRADA_SALIDA=0)
GROUP BY gc.GES_PERSONAL_ID,gc.FPVAL,gc.ENTRADA_SALIDA
ORDER BY gc.FPVAL, CASE gc.ENTRADA_SALIDA WHEN 1 THEN gc.FH END ASC, CASE WHEN gc.ENTRADA_SALIDA = 0 THEN gc.FH END DESC

此查询的结果是:

+------+------------+---------------------+------+
| pid  | fpval      | fh                  | es   |
+------+------------+---------------------+------+
|  138 | 2013-12-25 | 2013-12-25 14:29:00 |    0 |
|  138 | 2013-12-25 | 2013-12-25 14:29:11 |    1 |
+------+------------+---------------------+------+

正如您所看到的,我没有在“es”字段中获得每个案例的第一个结果。

我需要的结果是:

+------+------------+---------------------+------+
| pid  | fpval      | fh                  | es   |
+------+------------+---------------------+------+
|  138 | 2013-12-25 | 2013-12-26 01:06:16 |    0 |
|  138 | 2013-12-25 | 2013-12-25 14:28:20 |    1 |
+------+------------+---------------------+------+

0 个答案:

没有答案