我正在尝试创建一个查询,该查询在执行时将显示日期、状态(其中有多个状态选项)以及该日期的事件数量(按状态区分)。
我能够创建一个查询来显示我想要的所有数据,但我得到了重复的日期。我认为做到这一点的方法是使用别名,但我不知道方法。我也尝试过 case 语句,但也没有成功。
SELECT cast(event_date AS date) AS date, count(event_status) AS amount, status
FROM events
GROUP BY date, status
现在这就是我得到的:
date | amount | status
---------------------------------------
2019-05-07 | 5 | YES
2019-05-07 | 1 | NO
2019-05-06 | 4 | YES
2019-05-05 | 3 | YES
2019-05-04 | 6 | YES
2019-05-04 | 2 | MAYBE
这就是我想要得到的:
date | POSITVE | Negative
---------------------------------------
2019-05-07 | 5 | 1
2019-05-06 | 4 | 0
2019-05-05 | 3 | 0
2019-05-04 | 6 | 2
任何不等于"is"的状态均为负。 有什么建议么? 只是为了澄清:我想要的输出只是选项之一,我知道可能有不同的方法来解决我的问题,但这很适合我。谢谢
最佳答案
您可以进行条件聚合:
select cast(event_date AS date) AS date,
sum(case when status = 'Yes' then 1 else 0 end) as Positive,
sum(case when status <> 'Yes' then 1 else 0 end) as Negative
from events e
group by cast(event_date AS date);
但是,mariaDB
有简写版本:
select cast(event_date AS date) AS date,
sum( status = 'Yes' ) as Positive,
sum( status <> 'Yes' ) as Negative
from events e
group by cast(event_date AS date);
关于sql - 如何避免 mysql 查询中出现重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038135/