2017-09-25 47 views
-1

對於每個EVENT_TYPE值被重複不止一次減法取決於時間SQL

enter image description here

我需要返回event_type併爲此event_type,註冊的最後一個值的減法SQL語句第二值。我感謝你的幫助

+1

這是一門功課? –

+1

什麼是您的DBMS? SQL Server? MySQL的?甲骨文?還有別的嗎? – Siyual

+0

這就是我所做的: select event_type,sum(case event.value having count(*) - events.value have count(*)= 2)作爲來自event_type具有count(*)> 1的事件的「value」 –

回答

0

可以使用LEAD()(或LAG()如果你喜歡),以獲得在該系列中的下一個記錄,並計算差值時,纔會有另一條記錄,只有採取每Event_Type最新Time

With Cte As 
(
    Select *, 
      Row_Number() Over (Partition By Event_Type Order By Time Desc) As Row_Number, 
      Lead(Value) Over (Partition By Event_Type Order By Time Desc) As Prev 
    From YourTable 
) 
Select Event_Type, Value - Prev As Value 
From Cte 
Where Prev Is Not Null 
And  Row_Number = 1 
0

我會用row_number()和有條件聚集:

select e.event_type, 
     sum(case when seqnum = 1 then value when seqnum = 2 then - value end) as diff 
from (select e.*, 
      row_number() over (partition by e.event_type order by e.time desc) as seqnum 
     from events e 
    ) e 
group by e.event_type 
having count(*) >= 2;