SQL按日期将多个值按日期汇总为新值

时间:2017-01-19 17:03:42

标签: mysql sql date sum

您好我的报告已经发布了一些规律性,但是当报告值为空时,它们具有帐户的初始值。 我想为学校,年份和日期创建一个新的变量Accts_N,它是该日期的Accts值和日期为null时的Accts值的总和。 因此,使用下面的示例表,2017学年A学校2016-01-10的Accts_N值为8,2016-02-10的值为12。

School | Year | Accts | ReportDate
-------|------|-------|-----------
A      | 2017 | 2     | null
A      | 2017 | 6     | 2016-01-10
A      | 2017 | 10    | 2016-02-10
A      | 2018 | 0     | 2016-01-10
A      | 2018 | 4     | 2016-02-10
B      | 2017 | 9     | null
B      | 2018 | 3     | 2016-2-10

我尝试了几种不同的SUM CASE WHEN实例,但我不认为这是正确的方法。有人可以为我指明一个方向吗? 谢谢

2 个答案:

答案 0 :(得分:1)

如果要添加新列,则会想到相关的子查询:

select r.*,
       (select sum(r2.accts)
        from reports r2
        where r2.school = r.school and
              r2.year = r.year and
              (r2.reportdate = r.reportdate or r2.reportdate is null)
      ) as accts_n
from reports r;

答案 1 :(得分:0)

这个怎么样?

  declare @t table(School nvarchar(50), Year datetime, Accts int, ReportDate datetime)

    insert into @t
    values
        ('A','2017',2,null),
        ('A','2017',6,'2016-01-10'),
        ('A','2017',10,'2016-02-10'),
        ('A','2018',0,'2016-01-10'),
        ('A','2018',4,'2016-02-10'),
        ('B','2017',9,null),
        ('B','2018',3,'2016-01-10')

    select t.School, t.Year, t.ReportDate, t.Accts + ISNULL(tNulls.SumAcctsWhenNull,0)
    from @t t
        outer apply (select t2.School, t2.Year, SUM(Accts) AS SumAcctsWhenNull
                    from @t t2
                    where
                        t2.ReportDate IS NULL AND
                        t2.School = t.School AND
                        t2.Year = t.Year
                    group by t2.School, t2.Year) tNulls
    where
        t.ReportDate IS NOT NULL