我正在尝试计算 l_events
表的 subchannel
列中 2013-10-01
和2014-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/