根据包含CustomerID,Date和Daily Sales字段的表,我需要计算每个CustomerID,Date组合的前7天销售额。样本数据如下:
CustomerID Date Daily Sales
1 10/18/16 $100
1 10/17/16 $50
1 9/1/16 $20
1 8/5/16 $20
1 7/1/16 $20
1 6/15/16 $20
1 1/1/16 $20
2 10/18/16 $50
2 10/17/16 $50
2 10/16/16 $50
2 10/15/16 $50
2 10/14/16 $50
所需的输出如下:
CustomerID Date Daily Sales Last 7 Days Sales
1 10/18/16 $100 $150
1 10/17/16 $50 $50
1 9/1/16 $20 $20
1 8/5/16 $20 $20
1 7/1/16 $20 $20
1 6/15/16 $20 $20
1 1/1/16 $20 $20
2 10/18/16 $50 $250
2 10/17/16 $50 $200
2 10/16/16 $50 $150
2 10/15/16 $50 $100
2 10/14/16 $50 $50
以下是我正在使用的查询:
SELECT
t1.[CustomerID]
,CAST(t1.[Date] AS DATE) AS Date
,SUM(t1.[DailySales]) AS [DailySales]
,SUM(t2.[DailySales]) AS [Last7DaysSales]
FROM TABLE_NAME t1 LEFT OUTER JOIN TABLE_NAME t2 ON t1.[CustomerID] = t2.[CustomerID]
AND CAST(t2.[Date] AS DATE) BETWEEN DATEADD(DAY, -7, t1.[Date]) and t1.[Date]
GROUP BY t1.[CustomerID], CAST(t1.[Date] AS DATE)
ORDER BY t1.[CustomerID], CAST(t1.[Date] AS DATE) DESC;
为Last7DaysSales按预期返回值,但仅对当天的销售不正确。我确定我正在做一些愚蠢的事情导致这个问题......
答案 0 :(得分:0)
SELECT SUM(Column) FROM TABLE_NAME WHERE date < (GETDATE()-7) AND CustomerId=1
- 为您提供客户ID = 1的每日销售额。
答案 1 :(得分:0)
您可以构造基本查询以获取除Last7DaysSales值之外的所有内容,然后使用子查询计算它:
SELECT
t1.[CustomerID]
,CAST(t1.[Date] AS DATE) AS Date
,SUM(t1.[DailySales]) AS [DailySales]
,(select sum(t2.[DailySales])
from TABLE_NAME t2
where t1.CustomerID = t2.CustomerID
and cast(t2.[Date] as date) between dateadd(day, -7, cast(t1.[Date] as date)) and cast(t1.[Date] as date)
) as [Last7DaysSales]
FROM TABLE_NAME t1 LEFT OUTER JOIN TABLE_NAME t2 ON t1.[CustomerID] = t2.[CustomerID]
AND CAST(t2.[Date] AS DATE) BETWEEN DATEADD(DAY, -7, t1.[Date]) and t1.[Date]
GROUP BY t1.[CustomerID], CAST(t1.[Date] AS DATE)
ORDER BY t1.[CustomerID], CAST(t1.[Date] AS DATE) DESC;
请注意,窗口函数是一种更有效的方法,但这种方法可能更直观一些。