mysql 为列中每个特定值填充缺失的日期

标签 mysql sql

我正在尝试计算 l_events 表的 subchannel 列中 2013-10-012014-03-31 并按特定子 channel 进行分组。

现在我的结果如下:

year    month   subchannel      count(*)
2013      10    creativemornings    1
2014       3    creativemornings    2
2013      11    founderinstitute    1

我希望我的结果包含每个特定子 channel 的行,其中该月没有发生任何事件。所以类似:

year    month   subchannel      count(*)
2013      10    creativemornings    1
2013      11    creativemornings    0
2013      12    creativemornings    0
2014       1    creativemornings    0
2014       2    creativemornings    0
2014       3    creativemornings    2
2013      10    founderinstitute    0
2013      11    founderinstitute    1
2013      12    founderinstitute    0
2014       1    founderinstitute    0
2014       2    founderinstitute    0
2014       3    founderinstitute    0

我尝试将查询加入日历表(其中包括所有相关日期的日期时间列),但它不起作用。有什么想法吗?

    SELECT  
        year(l.created) as year,
        month(l.created) as month,
        l.subchannel,
        count(*)

    FROM db.l_events l

    right JOIN db.calendar c 
        ON (date(l.created) = c.datefield)

    WHERE  
         l.created between '2013-10-01' and '2014-03-31' 

    group by
        l.subchannel,
        year(l.created), 
        month(l.created)
        ;

最佳答案

这样就可以了。它会创建您的子 channel 列表和日历表的笛卡尔积,并将 l_events 表左连接到该结果集。

SELECT  
    year(c.datefield) as year,
    month(c.datefield) as month,
    s.subchannel,
    count(l.created)
FROM db.calendar c
    CROSS JOIN (select distinct subchannel from l_events) s
    LEFT JOIN db.l_events l
        ON (date(l.created) = c.datefield)
        AND l.subchannel = s.subchannel
Where c.datefield between '2013-10-01' and '2014-03-31' 
group by
    s.subchannel,
    year(c.created), 
    month(.created)
order by
    s.subchannel,
    year(c.created), 
    month(.created)
    ;

关于mysql 为列中每个特定值填充缺失的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22922186/

相关文章:

mysql - MySQL 中 MATCH ('...' IN NATURAL LANGUAGE MODE) 的最大可能取值范围是多少?

mysql - 使用参数 Delphi XE7 Firedac

sql - Oracle SQL - 选择前 n 个不同的行

php - MySQL 查询 - 将 BLOB 的结果限制为 blob(行)中的 1 个唯一元素

mysql - 在 Eclipse 中单击按钮创建表

android - 忽略重音 SQLite3

mysql - 元表 VS 字段多、规模大的表。性能方面

sql - 比较记录集中的 2 个连续行

mysql - 如何在 laravel 的 Controller 中编写普通的 sql 查询

sql - 如何使用 Postgres SQL 获取具有单个总计行的同一列的不同值的计数?