我一直在尋找這個,並試圖使此代碼工作一個星期了。累積計數與組的情況下當
我的數據集tbSubscriptions
有列:
Subscription_Date (dd/mm/yyyy hh:mm:ss)
Subscription_Id (char 6)
Subscription_Type (char 1)
要檢索每週訂閱數使用:
select
datepart(wk,Subscription_Date) as WeekNo,
sum(case when Subscription_Type = 1 then 1 else 0 end) as TotalSubcriptions
from tbSubscriptions
group by datepart(wk,Subscription_Date)
order by 1
該查詢將返回:
WeekNo |Total Subscriptions
21 |12
22 |13
23 |8
24 |18
我想要返回的查詢:
WeekNo |CumulativeSubscriptions
21 |12
22 |25 (=12+13)
23 |33 (=25+8)
24 |51 (=33+18)
下面是一個簡單的數據集創建腳本:
GO
IF OBJECT_ID('tbSubscriptions') IS NOT NULL
DROP TABLE tbSubscriptions
GO
CREATE TABLE tbSubscriptions (Subscription_Id INT, Subscription_Date datetime, Subscription_Type INT)
GO
INSERT INTO tbSubscriptions (Subscription_Id, Subscription_Date, Subscription_Type)
VALUES
(1, convert(datetime,'01-08-16 00:00:00 AM',5),1),
(2, convert(datetime,'15-08-16 00:00:00 AM',5),1),
(3, convert(datetime,'01-09-16 00:00:00 AM',5),1),
(4, convert(datetime,'09-09-16 00:00:00 AM',5),1),
(5, convert(datetime,'18-09-16 00:00:00 AM',5),0),
(6, convert(datetime,'15-10-16 00:00:00 AM',5),1),
(7, convert(datetime,'22-10-16 00:00:00 AM',5),0),
(8, convert(datetime,'23-10-16 00:00:00 AM',5),0),
(9, convert(datetime,'01-11-16 00:00:00 AM',5),1),
(10, convert(datetime,'02-11-16 00:00:00 AM',5),1),
(11, convert(datetime,'14-11-16 00:00:00 AM',5),0),
(12, convert(datetime,'01-12-16 00:00:00 AM',5),1),
(13, convert(datetime,'02-12-16 00:00:00 AM',5),1),
(14, convert(datetime,'05-12-16 00:00:00 AM',5),1),
(15, convert(datetime,'09-12-16 00:00:00 AM',5),1),
(16, convert(datetime,'10-12-16 00:00:00 AM',5),1),
(17, convert(datetime,'11-12-16 00:00:00 AM',5),1),
(18, convert(datetime,'19-12-16 00:00:00 AM',5),0),
(19, convert(datetime,'25-12-16 00:00:00 AM',5),0),
(20, convert(datetime,'29-12-16 00:00:00 AM',5),0);
GO
我已經嘗試了累積和兩種方法(窗口功能和自我加盟),但不能去上班。
任何幫助將不勝感激。
親切的問候, 保羅。
它 保護正常工作「SELECT DATEPART(WK,Subscription_Date), ( \t SELECT COUNT(Subscription_Id) \t FROM tbSubscriptions T2 \t WHERE日期部分(WK,t2.Subscription_Date)<=日期部分(WK,t1.Subscription_Date)和 t2.Subscription_Type = 1 )AS running_total FROM tbSubscriptions T1 WHERE \t t1.Subscription_Type = 1 GROUP BY datepart(wk,t1.Subscription_Date) ORDER BY datepart(wk,t1.Subscription_Date)「 –