2014-04-07 51 views
0

失蹤日期爲每個特定的價值我想數清我l_events表的日期2013-10-012014-03-31和組之間的subchannel列事件按特定subchannelyearmonth的數量。MySQL的填補了

現在我的結果是這樣的:

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

,我想我的結果包括在沒有發生的事件發生當月每一個具體的子信道行。因此,像:

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) 
     ; 

回答

1

這樣做。它會創建子通道列表和日曆表的笛卡爾積,並且將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) 
    ;