mysql - 在mysql中的列中拆分日期
问题描述
我有一个事件执行表,其中我想根据日期分隔列
SELECT Event_ID,Name,count(Customer_Id) FROM UNLIMITED.Event_Execution a
join UNLIMITED.Event_Master b on a.Event_Id=b.ID
Where Event_Execution_Date_ID = '20211007'
group by Event_Id
order by Count(Customer_Id) desc;
期望的输出
Event_ID Name 20211006 20211007
1 Offer1 1,218 6,876
2 Offer2 10,212 4,123
解决方案
你想要条件聚合:
select
event_id,
name,
count(case when event_execution_date_id = '20211006' then customer_id end) as cnt_20211006,
count(case when event_execution_date_id = '20211007' then customer_id end) as cnt_20211007
from unlimited.event_execution a
join unlimited.event_master b on a.event_id = b.id
where event_execution_date_id in ('20211006', '20211007')
group by event_id
order by count(customer_id) desc;
旁注:
- a 和 b 是错误的别名。使用一些助记符,例如 e 用于执行表,m 用于主表。
- 处理多个表时,限定所有列。
customer_id
例如,属于哪个表? - 为什么
count(customer_id)
?客户 ID 是可为空的列吗?或者它是否驻留在执行表中,并且您希望能够在某个时间外连接该表并获得正确的零计数?或者计算一个表达式而不仅仅是行(count(*)
)的原因是什么?
推荐阅读
- java - 我可以将字节数组转换为位图,但反向相同的过程会产生空值
- c# - 如何使用 dotnet 核心加密具有多个 x509 证书的短信
- javascript - 变量范围的精确定义是什么(在 JavaScript 中)?
- javascript - Jquery:用户完成输入后的操作
- python - 带有树的Python Sklearn - 发现样本数量不一致的输入变量
- docker - Docker 容器链接
- postgresql - {"Parameter must have its value set"} 处理 NPGSQL 中可能的空值
- python - 当我使用变量而不是列表时出现“IndexError:元组索引超出范围”
- c# - Write temp file and move to .ini file via interface causes Error in C#
- scala - Scala - 如何使用来自猫的 Validated monad 验证列表中的每个字符串?