如何对表数据进行分组?

时间:2014-08-15 20:28:39

标签: mysql

我有一张桌子:

mysql> select * from playground order by locatedAt;
+------------+---------------------+--------------+
| macAddress | locatedAt           | status       |
+------------+---------------------+--------------+
| device1    | 2014-08-11 01:20:27 | connected    |
| device2    | 2014-08-11 01:20:27 | connected    |
| device2    | 2014-08-11 01:30:27 | disconnected |
| device1    | 2014-08-11 01:30:27 | connected    |
| device2    | 2014-08-11 01:40:27 | disconnected |
| device1    | 2014-08-11 01:40:27 | disconnected |
| device2    | 2014-08-11 01:49:27 | connected    |
| device1    | 2014-08-11 01:49:27 | connected    |
| device1    | 2014-08-11 01:50:27 | disconnected |
| device2    | 2014-08-11 01:53:27 | disconnected |
| device1    | 2014-08-11 01:55:27 | disconnected |
| device1    | 2014-08-11 02:05:27 | disconnected |
| device2    | 2014-08-11 02:10:27 | disconnected |
| device2    | 2014-08-11 02:15:27 | disconnected |

我需要对数据进行汇总,以便按一天中的小时和设备的状态进行分组。预期产出:

hour | connected | disconnected
01   |  5        | 6
02   |  0        | 3

我该怎么做?

1 个答案:

答案 0 :(得分:2)

做到这一点。使用函数HOUR获取locateAt列的小时总结状态值,并按DATE部分和locateAt列的HOUR部分进行分组:

SELECT
    HOUR(locatedAt) hour,  
    SUM(CASE WHEN status='connected' THEN 1 ELSE 0 END) connected,
    SUM(CASE WHEN status='disconnected' THEN 1 ELSE 0 END) disconnected
FROM
    playground
GROUP BY 
    DATE(locatedAt), HOUR(locatedAt);

你可以像草莓一样简化表达:

SELECT
    HOUR(locatedAt) hour,  
    SUM(status='connected') connected,
    SUM(status='disconnected') disconnected
FROM
    playground
GROUP BY 
    DATE(locatedAt), HOUR(locatedAt);

因为MySQL TRUE实现为1而FALSE实现为0,请参阅Logical Operators

  

在SQL中,所有逻辑运算符的计算结果为TRUE,FALSE或NULL   (未知)。在MySQL中,这些实现为1(TRUE),0(FALSE)和   NULL。

使用fiddle