当前日期栏旁边的上一个日期值

时间:2019-09-11 20:05:51

标签: sql sql-server

我有一张桌子,上面有每天的仪表读数值。首先,我想要给定日期的所有仪表读数的总和。使用group by子句很容易实现。我无法执行的操作是获取表中上一个日期的仪表读数的总和。

原始数据:

Ddate      ---- Value
2019-09-11 ---- 10
2019-09-11 ---- 20
2019-09-11 ---- 30
2019-09-10 ---- 15
2019-09-10 ---- 15
2019-09-10 ---- 15
2019-09-09 ---- 10
2019-09-09 ---- 5
2019-09-09 ---- 35

Select Ddate,Sum(MeterValue) as SumToday From @MyTable
group by Ddate

当前日期的总和:

Ddate      ---- SumToday
2019-09-11 ---- 60
2019-09-10 ---- 45
2019-09-09 ---- 50

这是我要实现的最终表:

Ddate      ---- SumToday ---- SumYesterday ---- difference
2019-09-11 ---- 60       ---- 45           ---- 15
2019-09-10 ---- 45       ---- 50           ---- -5
2019-09-09 ---- 50       ---- NULL         ---- 50

请注意,我仅对差异列感兴趣,不带“ SumYesterday”列的解决方案是可以接受的。

3 个答案:

答案 0 :(得分:1)

您可以在ERROR: Unable to create new service: ChromeDriverService Build info: version: '3.141.0', revision: '2ecb7d9a', time: '2018-10-31T20:22:52' System info: host: '<me>', ip: '<my_ip>', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '1.8.0_212' Driver info: driver.version: unknown 查询中直接使用lag()

group by

注意:这假定“昨天”始终可用。如果不是-您的意思是昨天而不是前一天-那么就需要更多逻辑:

select Ddate, Sum(MeterValue) as SumToday,
       lag(sum(MeterValue)) over (order by Ddate) as prev_day,
       (sum(MeterValue) - lag(sum(MeterValue, 1, 0)) over (order by Ddate)) as diff
From @MyTable
group by Ddate;

答案 1 :(得分:0)

这是一个可以为您提供答案的查询

select Ddate, SumToday, SumYesterday, SumToday - SumYesterday as [Difference]
from (
   select t.Ddate
     ,sum(t.MeterValue) as SumToday
     ,(select sum(MeterValue) from @MyTable t2 where t2.Ddate = dateadd(day, -1, t.Ddate)) as SumYesterday
   from @MyTable t
   group by t.Ddate) t

答案 2 :(得分:0)

将查询作为CTE并自行加入:

with cte as (
  select Ddate, sum(MeterValue) as SumToday from tablename
  group by Ddate
)
select 
  c1.*, c2.SumToday as SumYesterday, c1.SumToday - coalesce(c2.SumToday, 0) difference
from cte c1 left join cte c2
on c2.Ddate = c1.Ddate - 1
order by c1.Ddate desc

或使用lag()窗口功能:

with cte as (
  select Ddate, sum(MeterValue) as SumToday from tablename
  group by Ddate
)
select *,
  lag(SumToday) over (order by Ddate) as SumYesterday, 
  SumToday - coalesce(lag(SumToday) over (order by Ddate), 0) as difference
from cte 
order by Ddate desc

请参见demo
结果:

Ddate               | SumToday | SumYesterday | difference
:------------------ | -------: | -----------: | ---------:
11/09/2019          |       60 |           45 |         15
10/09/2019          |       45 |           50 |         -5
09/09/2019          |       50 |              |         50