我有一张这样的桌子:
state date
new 01/01/2018
new 02/01/2018
active 05/01/2018
active 09/01/2018
active 10/01/2018
new 12/01/2018
active 13/01/2018
active 14/01/2018
close 15/01/2018
每个状态的最小日期,我需要在状态栏中进行任何更改。
决赛桌:
state date
new 01/01/2018
active 05/01/2018
new 12/01/2018
close 15/01/2018
如何在SQL中做到这一点?
答案 0 :(得分:1)
由于您尚未标记任何DBMS,所以我会选择row_number()
,因为它似乎是gaps-and-islands
的问题:
select state, min(date)
from (select t.*,
row_number() over (order by date) as seq1,
row_number() over (partition by state order by date) as seq2
from table t
) t
group by state, (seq1-seq2);
答案 1 :(得分:1)
这是使用WITH和LAG的解决方案
WITH state_change (state, st_date, next_state) AS
(SELECT state , st_date,
LAG(state, 1, '') OVER(ORDER BY st_date) as s2
FROM table
)
SELECT state, st_date
FROM state_change
WHERE state != next_state
ORDER BY st_date ASC
输出(包括激活的第二个更改)
state st_date
new 2018-01-01
active 2018-01-05
new 2018-01-12
active 2018-01-14
close 2018-01-15