我有以下数据.
WM_Week POS_Store_Count POS_Qty POS_Sales POS_Cost ------ --------------- ------ -------- -------- 201541 3965 77722 153904.67 102593.04 201542 3952 77866 154219.66 102783.12 201543 3951 70690 139967.06 94724.60 201544 3958 70773 140131.41 95543.55 201545 3958 76623 151739.31 103441.05 201546 3956 73236 145016.54 98868.60 201547 3939 64317 127368.62 86827.95 201548 3927 60762 120309.32 82028.70
我需要写一个SQL查询来获取过去四周的数据,并总结出以下每个列的最后四周:POS_Store_Count
,POS_Qty
,POS_Sales
,和POS_Cost
.
例如,如果我想要201548的数据,它将包含201548,201547,20156和201545.
201547的总和将包含201547,201546,20155和201544.
成功运行时,查询应返回4行.
我如何制定递归查询来执行此操作?这样做有什么比递归更简单吗?
编辑:版本是Azure Sql DW,版本号为12.0.2000.Edit2:应该返回的四行将包含自己的列的总和,并且它是前三周的列.
例如,如果我想要201548的数字,它将返回以下内容:
WM_Week POS_Store_Count POS_Qty POS_Sales POS_Cost ------ --------------- ------- -------- -------- 201548 15780 274938 544433.79 371166.3
这是四(非标识)列从总和201548
,201547
,201546
,和201545
.
很确定这会得到你想要的东西..我在订购数据后使用交叉申请来应用SUMS
Create Table #WeeklyData (WM_Week Int, POS_Store_Count Int, POS_Qty Int, POS_Sales Money, POS_Cost Money) Insert #WeeklyData Values (201541,3965,77722,153904.67,102593.04), (201542,3952,77866,154219.66,102783.12), (201543,3951,70690,139967.06,94724.6), (201544,3958,70773,140131.41,95543.55), (201545,3958,76623,151739.31,103441.05), (201546,3956,73236,145016.54,98868.6), (201547,3939,64317,127368.62,86827.95), (201548,3927,60762,120309.32,82028.7) DECLARE @StartWeek INT = 201548; WITH cte AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY [WM_Week] DESC) rn FROM #WeeklyData WHERE WM_Week BETWEEN @StartWeek - 9 AND @StartWeek ) SELECT * FROM cte c1 CROSS APPLY (SELECT SUM(POS_Store_Count) POS_Store_Count_SUM, SUM(POS_Qty) POS_Qty_SUM, SUM(POS_Sales) POS_Sales_SUM, SUM(POS_Cost) POS_Cost_SUM FROM cte c2 WHERE c2.rn BETWEEN c1.rn AND (c1.rn + 3) ) ca WHERE c1.rn <= 4