SQL组数据分为Year + Week Number bin

时间:2015-09-07 10:22:52

标签: mysql sql mysql-workbench

我有一份企业名单和他们的创建日期,我想把它们分成年份+周数的分类 - 但问题是,如果在2015年的第1周没有创建企业,我仍然希望它显示这个bin有' 0'。

以下查询会跳过没有创建商家的周数:

SELECT Date_Format(created,'%X %V') as d, count(*) as Biz
FROM businesses b
GROUP BY d
ORDER BY d asc

任何人都知道如何添加丢失的垃圾箱并使其保持动态?这意味着,当我在2周内运行它时,即使在这两周内没有创建任何业务,我也会获得2个新的箱柜。 谢谢!

1 个答案:

答案 0 :(得分:0)

尝试附加查询

select 
Date_Format(M1,'%X %V'),count(b.*)
from
(
select 
'2015-01-01'  +INTERVAL m WEEK as m1
from
(
select @rownum:=@rownum+1 as m from
(select 1 union select 2 union select 3 union select 4) t1,
(select 1 union select 2 union select 3 union select 4) t2,
(select 1 union select 2 union select 3 union select 4) t3,
(select @rownum:=-1) t0
) d1
) d2
LEFT JOIN businesses b on Date_Format(b.created,'%X %V')=Date_Format(M1,'%X %V')
group by
Date_Format(M1,'%X %V')
order by m1