【问题标题】:List grouped data by month including months in which there are no results按月列出分组数据,包括没有结果的月份
【发布时间】:2017-12-01 20:09:19
【问题描述】:

Hello community 以下查询将每个活动状态的出现次数相加,然后按月分组

select
    date_format(date_created, '%b') month,
    month(date_created) pivot,
    sum(case when a.state = 'created' then 1 else 0 end) created,
    sum(case when a.state = 'notified' then 1 else 0 end) notified,
    sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
    sum(case when a.state = 'approved' then 1 else 0 end) approved,
    sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
    sum(case when a.state = 'attended' then 1 else 0 end) attended,
    sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
    count(a.id) as total
from activities a
group by 1 order by pivot desc;

所以我得到以下结果

我想在这个结果中添加没有数据的月份,并用零自动完成状态总和

我分享这个sqlfiddle

我发现这个answer 用于类似的场景,但我不明白如何将它应用到我向您展示的案例中

非常感谢您的帮助

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以使用日期表(子查询)和LEFT JOIN

    select
        s.name month,
        s.m pivot,
        sum(case when a.state = 'created' then 1 else 0 end) created,
        sum(case when a.state = 'notified' then 1 else 0 end) notified,
        sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
        sum(case when a.state = 'approved' then 1 else 0 end) approved,
        sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
        sum(case when a.state = 'attended' then 1 else 0 end) attended,
        sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
        count(a.id) as total
    from (SELECT  1 m, 'Jan' AS name 
          UNION SELECT 2, 'Feb' 
          UNION SELECT 3, 'Mar'
          UNION ...) s
    LEFT JOIN activities a
      ON s.m = month(date_created)
      --AND s.y = year(date_created)   -- if needed 
    group by 1
    order by pivot desc;
    

    DBFiddle Demo

    【讨论】:

    • 非常感谢。这正是我想要的结果。
    • @user615274 请注意,如果您有多年的数据,您需要添加带有年份的第 3 列以避免聚合来自 2 个不同年份的数据。
    • 请您发表您的评论。
    • @user615274 例如,您有来自JAN 2017JAN 2016 的数据。如果您只使用month(created_date),那么两个JAN 将被聚合为一组。
    • 我相信这种情况在数据库中得到了有效的解决,我避免了按月分组的聚合消息和pivotgroup by 1, 2。您认为从长远来看是一个正确的解决方案吗?
    猜你喜欢
    • 2017-10-29
    • 2011-12-21
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2023-03-15
    相关资源
    最近更新 更多