简体   繁体   English

将SQL组数据放入Year + Week Number箱中

[英]SQL group data into Year + Week Number bins

I have a list of businesses and their creation date, and I want to group them into bins of year + week number - but the catch is that if there were no businesses created in week 1 in 2015 i still want it to show this bin with '0'. 我有一个企业及其创建日期的列表,我想将它们分组为年份+周数的箱-但是要注意的是,如果2015年第1周没有创建任何企业,我仍然希望它显示此箱'0'。

The following query skips weeks that there were no businesses created: 以下查询跳过了没有创建任何业务的几周:

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

Anyone know How I can add the missing bins and keep it dynamic? 有人知道如何添加丢失的垃圾箱并保持动态吗? meaning that when I run it in 2 weeks I'll get 2 new bins even if there were no businesses created in those 2 weeks. 这意味着当我在2周内运行它时,即使在这2周内没有创建任何公司,我也会获得2个新垃圾箱。 Thanks! 谢谢!

Try the attached query 尝试附加的查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM