我试图按期间对一堆日期进行分组,即" month"
首先我宣布表:
--inserts 36 dates every 10 days
create table sales (sales_date datetime, sales_amount decimal(12,2))
insert into sales (sales_date,sales_amount)
select '20140101',1000 union all
select '20140110',1000 union all
select '20140120',1000 union all
select '20140130',1000 union all
...
然后我查询按句点(大小=精确*月)
分组的条目DECLARE @precision int = 1 --number of months
SELECT
dateadd(month, (datediff(month, 0, sales_date) / @precision) * @precision, 0) as FromDate,
dateadd(month, @precision + (datediff(month, 0, sales_date) / @precision) * @precision, 0) as ToDate,
count(*) as number
FROM sales
GROUP BY
dateadd(month, (datediff(month, 0, sales_date) / @precision) * @precision, 0),
dateadd(month, @precision + (datediff(month, 0, sales_date) / @precision) * @precision, 0)
结果:
Test 1 : precision of 1 month
From : 01/01/2014, To : 01/02/2014, number : 4
From : 01/02/2014, To : 01/03/2014, number : 2
From : 01/03/2014, To : 01/04/2014, number : 3
From : 01/05/2014, To : 01/06/2014, number : 4
From : 01/06/2014, To : 01/07/2014, number : 3
From : 01/07/2014, To : 01/08/2014, number : 3
From : 01/08/2014, To : 01/09/2014, number : 3
From : 01/09/2014, To : 01/10/2014, number : 3
From : 01/10/2014, To : 01/11/2014, number : 3
From : 01/11/2014, To : 01/12/2014, number : 3
From : 01/12/2014, To : 01/01/2015, number : 2
Test 2 : precision of 2 months
From : 01/01/2014, To : 01/03/2014, number : 6
From : 01/03/2014, To : 01/05/2014, number : 6
From : 01/05/2014, To : 01/07/2014, number : 7
From : 01/07/2014, To : 01/09/2014, number : 6
From : 01/09/2014, To : 01/11/2014, number : 6
From : 01/11/2014, To : 01/01/2015, number : 5
Test 3 : precision of 3 months
From : 01/01/2014, To : 01/04/2014, number : 9
From : 01/04/2014, To : 01/07/2014, number : 10
From : 01/07/2014, To : 01/10/2014, number : 9
From : 01/10/2014, To : 01/01/2015, number : 8
Test 4 : precision of 4 months
From : 01/01/2014, To : 01/05/2014, number : 12
From : 01/05/2014, To : 01/09/2014, number : 13
From : 01/09/2014, To : 01/01/2015, number : 11
在测试5之前一切正常:
Test 5 : precision of 5 months
From : 01/10/2013, To : 01/03/2014, number : 6
From : 01/03/2014, To : 01/08/2014, number : 16
From : 01/08/2014, To : 01/01/2015, number : 14
第一行很烦人,我需要它像2014年1月1日一样开始,就像之前的精度一样
有没有办法克服这个问题?
答案 0 :(得分:0)
您不需要精确划分并再次乘以FROM
列的精确度
这是正在发生的事情
datediff(month, 0, sales_date)/5 -> 273.6 as it is integer division, it is converting to 273
进一步乘以273*5 = 1365
(因为整数除法会损失3个月)
所以这个应该适合你
DECLARE @precision int = 5 --number of months
SELECT
dateadd(month, (datediff(month, 0, sales_date) ) , 0) as [From],
dateadd(month, @precision + (datediff(month, 0, sales_date) ) , 0) as [To],
count(*) as number
FROM sales
GROUP BY
dateadd(month, (datediff(month, 0, sales_date) ) , 0),
dateadd(month, @precision + (datediff(month, 0, sales_date) ), 0)