MySQL将COUNT排序到不同的列中

时间:2013-11-26 13:34:16

标签: mysql

我有以下表结构

ID | capacity | startDateTime      
1  | 2        | 2013-11-26 13:23:23
2  | 3        | 2013-11-26 14:23:21
3  | 2        | 2013-11-26 13:44:44
4  | 6        | 2013-11-26 14:24:22 

我正在尝试将容量类别的ID计数分为小时和30分钟。

我输出的一个例子是

Hour | Minute | Capacity1-2 | Capacity3-4 | Capacity5above
13   | 0      | 1           | 0           | 0
13   | 1      | 1           | 0           | 0
14   | 0      | 0           | 1           | 1

Minute=0适用于ID在{30}分钟之前startDateTime(例如13:00:00至13:29:29)且Minute=1为对于ID s,在第30分钟之后使用`startDateTime。

我已经写到这样的东西,但它给了我总交易。我在将容量类别分成不同的列时遇到问题。

SELECT HOUR(startDateTime) AS Hour, 
  FLOOR(MINUTE(startDateTime)/30) AS Minute,
  COUNT(DISTINCT ID) as numTransactions 
  FROM transaction t 
  WHERE startDateTime >= '2013-11-26 00:00:00'
   AND queueStartTime <= '2013-11-26 23:59:59'  
  GROUP BY HOUR(startDateTime), FLOOR(MINUTE(startDateTime)/30)

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT HOUR(startDateTime) AS Hour,
  FLOOR(MINUTE(startDateTime) / 30) AS Minute,
  SUM(CASE WHEN capacity = 1 OR capacity = 2 THEN 1 ELSE 0 END) AS Capacity1_2,
  SUM(CASE WHEN capacity = 3 OR capacity = 4 THEN 1 ELSE 0 END) AS Capacity3_4,
  SUM(CASE WHEN capacity > 4 THEN 1 ELSE 0 END) AS Capacity5Above
FROM TRANSACTION t
WHERE startDateTime >= '2013-11-26 00:00:00'
  AND queueStartTime <= '2013-11-26 23:59:59'
GROUP BY HOUR(startDateTime),
  FLOOR(MINUTE(startDateTime) / 30)

对于与CASE WHEN验证匹配的每条记录而不是计数,这将改为SUM 1。这与每个容量范围的计数相同。