SQL-每列显示特定范围内的结果吗?

时间:2018-09-05 11:47:13

标签: sql sql-server tsql date

我正在尝试在SAP内部创建销售矩阵。

我要运行的SQL报告非常基础。它涉及以下内容:

SELECT 
    T1.ItemCode, SUM(T1.Quantity)
FROM
    OINV T0
INNER JOIN
    INV1 T1 ON T0.DocEntry = T1.DocEntry
WHERE
    ItemCode IS NOT NULL
    AND CardCode = 'C001500'
GROUP BY 
    T1.ItemCode
ORDER BY 
    T1.ItemCode

我希望将SUM(t1.quantity)字段分解成几周,但还不太清楚如何将其分解。

我想要Current Week将是daterangeGetdate()之间的Getdate()+7,然后是Week1将是Getdate()+8 To GetDate()+ 14`等...这将持续12周。

感谢您的帮助!

安迪

2 个答案:

答案 0 :(得分:0)

HAHA SQL中有一个WEEK()函数(我假设您正在使用SAP)。在该计算值上添加一个额外的GROUP BY应该可以解决问题。

https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.00/en-US/20f5758b7519101498b28e41757fe664.html

如果您使用的是mySAP,则它是SQL Server,而您需要的是DATEPART

https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017

答案 1 :(得分:0)

我现在已经编写了这段代码,但是SUM T1.Quantity不是总计。我看到AHV16在第5周售出一件商品,然后另一个实例AHV16在第2周售出一件商品,而AHV 16在第1-12周显示为NULL,在第12周总计显示1(这应该是第2周+第5周)。

SELECT T1.ItemCode
, '12 Week Total' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-84,Getdate()) AND T0.DocDate<=DateAdd(D,0,Getdate())))
, 'Current Week' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-7,Getdate()) AND T0.DocDate<=DateAdd(D,0,Getdate())))
, 'Week 2' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-14,Getdate()) AND T0.DocDate<=DateAdd(D,-8,Getdate())))
, 'Week 3' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-21,Getdate()) AND T0.DocDate<=DateAdd(D,-15,Getdate())))
, 'Week 4' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-28,Getdate()) AND T0.DocDate<=DateAdd(D,-22,Getdate())))
, 'Week 5' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-35,Getdate()) AND T0.DocDate<=DateAdd(D,-29,Getdate())))
, 'Week 6' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-42,Getdate()) AND T0.DocDate<=DateAdd(D,-36,Getdate())))
, 'Week 7' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-49,Getdate()) AND T0.DocDate<=DateAdd(D,-43,Getdate())))
, 'Week 8' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-56,Getdate()) AND T0.DocDate<=DateAdd(D,-50,Getdate())))
, 'Week 9' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-63,Getdate()) AND T0.DocDate<=DateAdd(D,-57,Getdate())))
, 'Week 10' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-70,Getdate()) AND T0.DocDate<=DateAdd(D,-64,Getdate())))
, 'Week 11' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-77,Getdate()) AND T0.DocDate<=DateAdd(D,-71,Getdate())))
, 'Week 12' = (SELECT sum(T1.Quantity) WHERE (T0.DocDate>=DateAdd(Day,-84,Getdate()) AND T0.DocDate<=DateAdd(D,-78,Getdate())))


    FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry

WHERE ItemCode IS NOT NULL and CardCode = 'C001500'
GROUP BY T1.ItemCode, T0.Docdate

Order By T1.ItemCode