如何在sql server 2008中获得上个月销售和本月销售 我的表结构是:
DailyDispatchID int Unchecked
Name varchar(50) Checked
Qty int Checked
Month varchar(50) Checked
我试过这个:
SELECT *
FROM (SELECT Name,
Gas,
Qty,
Month
FROM DailyDispatch) AS s
PIVOT (Sum(QTY)
FOR [month] IN(aug,
sep)) AS P
我正在获得输出,但它仅从8月和9月开始。它应该自动生成本月和之前的销售。如何解决这个问题。
答案 0 :(得分:1)
您需要根据当前月份和上个月在in子句中设置参数
答案 1 :(得分:0)
SELECT Name,
Gas,
Qty,
[Month]
FROM DailyDispatch
WHERE [Month] IN (SELECT CASE
WHEN Month(Getdate()) = 1 THEN 'jan'
WHEN Month(Getdate()) = 2 THEN 'feb'
WHEN Month(Getdate()) = 3 THEN 'mar'
WHEN Month(Getdate()) = 4 THEN 'apr'
WHEN Month(Getdate()) = 5 THEN 'may'
WHEN Month(Getdate()) = 6 THEN 'jun'
WHEN Month(Getdate()) = 7 THEN 'jul'
WHEN Month(Getdate()) = 8 THEN 'aug'
WHEN Month(Getdate()) = 9 THEN 'sep'
WHEN Month(Getdate()) = 10 THEN 'oct'
WHEN Month(Getdate()) = 11 THEN 'nov'
WHEN Month(Getdate()) = 12 THEN 'dec'
END [month]
UNION ALL
SELECT CASE
WHEN Month(Dateadd(mm, -1, Getdate())) = 1 THEN 'jan'
WHEN Month(Dateadd(mm, -1, Getdate())) = 2 THEN 'feb'
WHEN Month(Dateadd(mm, -1, Getdate())) = 3 THEN 'mar'
WHEN Month(Dateadd(mm, -1, Getdate())) = 4 THEN 'apr'
WHEN Month(Dateadd(mm, -1, Getdate())) = 5 THEN 'may'
WHEN Month(Dateadd(mm, -1, Getdate())) = 6 THEN 'jun'
WHEN Month(Dateadd(mm, -1, Getdate())) = 7 THEN 'jul'
WHEN Month(Dateadd(mm, -1, Getdate())) = 8 THEN 'aug'
WHEN Month(Dateadd(mm, -1, Getdate())) = 9 THEN 'sep'
WHEN Month(Dateadd(mm, -1, Getdate())) = 10 THEN 'oct'
WHEN Month(Dateadd(mm, -1, Getdate())) = 11 THEN 'nov'
WHEN Month(Dateadd(mm, -1, Getdate())) = 12 THEN 'dec'
END [month])