gpt4 book ai didi

mysql - 带有 COUNT 的子查询 (mysql)

转载 作者:行者123 更新时间:2023-11-29 05:23:20 24 4
gpt4 key购买 nike

我有下表:

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";

我很确定它需要是子查询,但在语法上苦苦挣扎!

最佳答案

您可以将 SUM 与条件一起使用,这将导致 bool 值并根据条件为您提供计数

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`)

Demo

关于mysql - 带有 COUNT 的子查询 (mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com