我有下表:
id | user | createdAt | pstatus
-------------------------------------------------------
287 | Foo | 2013-08-01 17:19:24 | PLAYING
286 | Foo | 2013-08-01 17:18:24 | IDLE
285 | Foo | 2013-08-01 17:17:24 | PLAYING
284 | Foo | 2013-08-01 17:16:24 | BUFFERING
283 | Foo | 2013-08-01 17:15:24 | STOPPED
如何查询此表以产生以下结果?基本上,我需要获得每个用户每天不同pstatus值的总数。
User | logdate | playCount | idleCount | bufferCount | StopCount
-------------------------------------------------------------------
Foo | 2013-08-01 | 48| 62 | 0 | 4
Foo | 2013-08-02 | 25| 22 | 0 | 0
Bar | 2013-08-02 | 22| 32 | 5 | 4
Bar | 2013-08-03 | 44| 11 | 1 | 0
Foo | 2013-08-03 | 32| 03 | 0 | 0
我知道我可以使用DATE(createdAt)来获取每天的日期而不是时间戳,但我正在努力将以下内容合并到一个查询中:
COUNT(pstatus) AS playCount WHERE pstatus = "PLAYING";
COUNT(pstatus) AS idleCount WHERE pstatus = "IDLE";
COUNT(pstatus) AS bufferCount WHERE pstatus = "BUFFERING";
COUNT(pstatus) AS StopCount WHERE pstatus = "STOPPED";
我很确定它需要是子查询,但在语法上挣扎!
答案 0 :(得分:3)
您可以使用SUM
条件,这将导致布尔值,并根据条件为您提供计数
SELECT
DATE(createdAt) logdate,
SUM(pstatus = "PLAYING") playCount
,SUM(pstatus = "IDLE") idleCount
,SUM(pstatus = "BUFFERING") bufferCount
,SUM(pstatus = "STOPPED") StopCount
FROM `table`
GROUP BY `User`,DATE(`createdAt`)
答案 1 :(得分:0)
试试这个:
SELECT
SUM(CASE
WHEN pstatus = "PLAYING" THEN 1
ELSE 0
END) AS sumPLAYING,
SUM(CASE
WHEN pstatus = "IDLE" THEN 1
ELSE 0
END) AS sumIDLE,
SUM(CASE
WHEN pstatus = "BUFFERING" THEN 1
ELSE 0
END) AS sumBUFFERING,
SUM(CASE
WHEN pstatus = "STOPPED" THEN 1
ELSE 0
END) AS sumSTOPPED
FROM YOUR_TABLE