【问题标题】:SQL - Previous Seven Days Sale (Per Customer, Per Date)SQL - 前 7 天销售(每个客户,每个日期)
【发布时间】:2016-10-19 05:15:30
【问题描述】:

基于包含 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 的值,但对于当天的销售额不正确。我确定我在加入导致问题的过程中做了一些愚蠢的事情......

【问题讨论】:

  • 欢迎来到 StackOverflow。您应该与我们分享您迄今为止所做的工作以及您面临的问题。请查看此页面以了解如何提出好的问题:stackoverflow.com/help/how-to-ask
  • 安德鲁,我的加入可能是个白痴(SQL 新手) - 通过这个查询,我能够正确获取 Last7DaysSales(每个客户,每个日期),但是它只是针对那个单独的日期返回了不正确的销售额!同样,我确定我是个白痴。我编辑了我的帖子以提供查询。

标签: sql-server sql-server-2012


【解决方案1】:

SELECT SUM(Column) FROM TABLE_NAME WHERE date < (GETDATE()-7) AND CustomerId=1 - 为您提供客户 id = 1 的每日销售额。

【讨论】:

  • 嗨,弗拉德 - 我需要返回数据集中每一天的每位客户前 7 天的销售额(而不是从 GETDATE() 开始的前 -7 天)
【解决方案2】:

您可以构建基本查询以获取除 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;

请注意,窗口函数是一种更有效的方法,但这种方法可能更直观一些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多