我有下表:
ID GroupID oDate oTime oValue
1 A 2014-06-01 00:00:00 100
2 A 2014-06-01 01:00:00 200
3 A 2014-06-01 02:00:00 300
4 A 2014-06-02 00:00:00 400
5 A 2014-06-02 01:00:00 425
6 A 2014-06-02 02:00:00 475
7 B 2014-06-01 00:00:00 1000
8 B 2014-06-01 01:00:00 1500
9 B 2014-06-01 02:00:00 2000
10 B 2014-06-02 00:00:00 3000
11 B 2014-06-02 01:00:00 3100
12 A 2014-06-03 00:00:00 525
13 A 2014-06-03 01:00:00 600
14 A 2014-06-03 02:00:00 625
我希望得到以下结果:
GroupID oDate oResult
A 2014-06-01 300
A 2014-06-02 125
B 2014-06-01 2000
oResult来自:
下午00:00:00的值减去00:00:00所选日期的值。
例如,我想知道2014-06-01
的结果。然后,
2014-06-02 00:00:00 400 substract 2014-06-01 00:00:00 100
oResult = 400 - 100 = 300
如何在SQL语法中实现此目的? 谢谢。
答案 0 :(得分:1)
您可以使用Common Table Expression
编写查询:
;with CTE as
( select row_number() over ( partition by GroupID, oDate order by oTime Asc) as rownum,
GroupID, oDate, oValue,oTime
from Test
)
select CTE.GroupID,CTE1.oDate, (CTE.oValue - CTE1.oValue) as oResult
from CTE
inner join CTE as CTE1 on datediff (day,CTE1.oDate, CTE.oDate) = 1
and CTE1.rownum= CTE.rownum
and CTE1.GroupID= CTE.GroupID
where CTE.rownum = 1
答案 1 :(得分:0)
您可以在此处使用cross apply
运算符
请检查一下,
select a.GroupID,a.oDate, (ab.oValue - a.oValue) oResult from T as a
cross apply
(
select top 1 * from T as b
where a.oDate < b.oDate
and oTime = '00:00:00.0000000'
and a.ID < b.ID
)as ab
where a.ID in(1,4,7)