使用SQL Server 2008和 使用'今天'值为12/5/2017用于临时数据目的。
我今天和一年前的今天(本周的同一天)拉动每家商店的总销售额。这就是我到目前为止所做的:
Declare @LastYearToday datetime, @Today datetime
-- @LastYearToday is business day on selected date, last year, same weekday
set @Today = '2017-12-5'
set @LastYearToday = Convert(date, (DATEADD(year, -1, getdate()+1)))
SELECT
StoreID, GrossSales, DF_BusinessDay
FROM DayFileSummary
WHERE
DF_BusinessDay = @LastYearToday OR
DF_BusinessDay = @Today
ORDER BY StoreID
我需要从去年的总销售额中扣除今天的总销售额,但我不确定如何继续。我是在SQL中执行此操作还是在报告中处理此操作?似乎报告需要一些逻辑来减去具有相同商店ID但不同日期的总销售额。我觉得我在想这个。
答案 0 :(得分:0)
你可以这样做:
WITH CTE
AS
(
SELECT
StoreID,
SUM(CASE WHEN DF_BusinessDay = @LastYearToday
THEN GrossSales ELSE 0 END) AS LastYearGrossSales
SUM(CASE WHEN DF_BusinessDay = @Today
THEN GrossSales ELSE 0 END) AS TodayGrossSales
FROM DayFileSummary
WHERE DF_BusinessDay = @LastYearToday OR DF_BusinessDay = @Today
GROUP BY StoreID
)
SELECT StoreID, LastYearGrossSales - TodayGrossSales AS Result
FROM CTE;
或:使用UNION
:
WITH CTE
AS
(
SELECT
StoreID, SUM(GrossSales) AS LastYearGrossSales, 0 AS TodayGrossSales
FROM DayFileSummary
WHERE DF_BusinessDay = @LastYearToday
GROUP BY StoreID
UNION ALL
SELECT StoreID, 0 AS LastYearGrossSales, SUM(GrossSales) AS TodayGrossSales
FROM DayFileSummary
WHERE DF_BusinessDay = @Today
)
SELECT StoreID, SUM(LastYearGrossSales) - SUM(TodayGrossSales) AS Result
FROM CTE
GROUP BY StoreID