如何从派生日期列创建求和值?

时间:2016-04-13 15:35:03

标签: sql sql-server sql-server-2012

尝试创建一些代码,根据派生日期汇总两个收入列,其中派生日期是相对于date_1的星期六。脚本的派生日期部分正在运行(在比我下面包含的更大的数据集上),但是,总和是在date_1之外,而不是派生日期。我包括一个带有代表性表格和一些插入行以及我当前拥有的代码的数据示例。 (这适用于SQL Server 2012.)

CREATE TABLE temp_1 (date_1 datetime, , rev_1 money, rev_2 money)

INSERT into temp1 VALUES (2015-12-22 00:00:00.000, 200, 300)
INSERT into temp1 VALUES (2015-12-23 00:00:00.000, 300, 400)
INSERT into temp1 VALUES (2015-12-24 00:00:00.000, 600, 700)
INSERT into temp1 VALUES (2015-12-28 00:00:00.000, 400, 500)
INSERT into temp1 VALUES (2015-12-29 00:00:00.000, 500, 600)
INSERT into temp1 VALUES (2015-12-30 00:00:00.000, 800, 900)
INSERT into temp1 VALUES (2015-12-31 00:00:00.000, 700, 800)

Select 
        DATEADD(DAY 
            ,  7 - (DATEPART(DW, CAST([date_1] as Date)))
            , CAST([date_1] as Date)) as 'Weekend Date',

        Round(Sum([rev_1]),2) as 'Rev1', 
        Round(SUM([rev_2]),2) as 'Rev2', 
        date_1 

    From temp_1

    Where [date_1] > '20151221' and [date_1] < '20160101'

Group by date_1
Order by 'Weekend Date' 

我的结果与前面插入的值相同。

期望的结果是(请注意这不包括列date_1):

Weekend Date   rev_1     rev_2
2015-12-26     1100      1400  
2016-01-02     2400      2800 

对此的任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:0)

您需要按所需的表达式进行聚合,而不仅仅是列:

Select DATEADD(DAY,
               7 - (DATEPART(DW, CAST([date_1] as Date)))
               CAST([date_1] as Date)
              ) as WeekendDate,
       Round(Sum([rev_1]), 2) as Rev1, 
       Round(SUM([rev_2]), 2) as Rev2, 
       date_1 
From temp_1
Where [date_1] > '20151221' and [date_1] < '20160101'
Group by DATEADD(DAY,
               7 - (DATEPART(DW, CAST([date_1] as Date)))
               CAST([date_1] as Date)
              )
Order by WeekendDate ;

我强烈建议您不要使用单引号作为列别名。命名规则:

  • 避免保留字(你这样做)。
  • 避免名字中的空格。
  • 使用方括号。