首页 > 解决方案 > 在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

标签: mysqlsqlcasemysql-workbench

解决方案


你想要条件聚合:

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(*))的原因是什么?

推荐阅读