[英]SQL, Group by one column
我有這樣的數據:
ID VERSION SEQUENCE
-------------- -------------- ---------------
01-001 01 001
01-002 01 002
02-002 02 002
而且我只想為每個序列選擇更高的版本,以便得到這樣的結果:
ID VERSION SEQUENCE
-------------- -------------- ---------------
01-001 01 001
02-002 02 002
我認為請求應該在Sequence上包含一個group by,但是我無法使其正常運行
有人可以幫忙嗎?
使用通用表表達式,您可以:
with HighestSequence(ID,MaxSequence)
as
(
select id, max(Sequence)
from table
group by ID
)
select t.*
from table t
inner join HighestSequence hs
on t.id = hs.id
and t.sequence = hs.sequence
因此,請篩選以僅包含版本為序列最高版本的那些行
Select id, version, sequence
From DataTable dt
where version =
(Select Max(version)
From DataTable
where Sequence = dt.Sequence)
您沒有指定DBMS,所以這是ANSI SQL:
select id, version, sequence
from (
select id, version, sequence,
row_number() over (partition by id order by sequence) as rn
from the_table
) t
where rn = 1
order by id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.