SQL总计PR组

时间:2018-08-23 11:46:32

标签: sql sql-server

我需要计算“每周过去6周内”的销售总额。 从今天起我需要:

  • 从今天开始1周前的销售总额。
  • 从今天起两周前的销售总额。
  • 从今天起三周前的销售总额。
  • ...直到6周后。

我有以下查询:

select retailerid,stylenumber,size,length,
    case when date > dateadd(WEEK,-1,GETDATE()) then SUM(quantity) else 0 end as w_1,
    case when date > dateadd(WEEK,-2,GETDATE()) then SUM(quantity) else 0 end as w_2,
    case when date > dateadd(WEEK,-3,GETDATE()) then SUM(quantity) else 0 end as w_3,
    case when date > dateadd(WEEK,-4,GETDATE()) then SUM(quantity) else 0 end as w_4,
    case when date > dateadd(WEEK,-5,GETDATE()) then SUM(quantity) else 0 end as w_5,
    case when date > dateadd(WEEK,-6,GETDATE()) then SUM(quantity) else 0 end as w_6        
    from someSalesTable
    left join dimdate on datekey = fk_date
    group by retailerid,stylenumber,size,length

错误是“日期”不在分组子句中,但是如何解决?

简单(但难看)的解决方法是进行6个不同的查询:/,但我需要一个结果来提供此信息,因为它将与另一个CTE结合在一起。

2 个答案:

答案 0 :(得分:1)

您应该let imageCroppedBg = imgWithClearBackgroung.cropAlpha() imageView.image = imageCroppedBg imageView.contentMode = .scaleAspectFit 整个;表达式,而不仅仅是SUM()

CASE WHEN

答案 1 :(得分:1)

如果您在使用quantity子句时有条件,则日期列应在聚合函数中:

select retailerid,stylenumber,size,length,
    SUM(case when date > dateadd(WEEK,-1,GETDATE()) then (quantity) else 0 end) as w_1,
    SUM(case when date > dateadd(WEEK,-2,GETDATE()) then (quantity) else 0 end) as w_2,
    SUM(case when date > dateadd(WEEK,-3,GETDATE()) then (quantity) else 0 end) as w_3,
    SUM(case when date > dateadd(WEEK,-4,GETDATE()) then (quantity) else 0 end) as w_4,
    SUM(case when date > dateadd(WEEK,-5,GETDATE()) then (quantity) else 0 end) as w_5,
    SUM(case when date > dateadd(WEEK,-6,GETDATE()) then (quantity) else 0 end) as w_6        
    from someSalesTable
    left join dimdate on datekey = fk_date
    group by retailerid,stylenumber,size,length