2017-10-17 73 views
1

我使用SQL Server 2012, 我有如下表:
id, name, surname, timestamp, type查找一行最大值兩組

type有兩個可能的值:12

現在,我想找到兩行 - 對於每個組(12)行具有最大值,特別是type。我想找到namesurname。 我可以用SELECT TOP 1 - WHERE ORDER BY - UNION的方法做到這一點,但我想找到antother,更好的主意。 你能幫我嗎?

+2

你可以給一些樣本數據和所需的輸出?將會更容易給出更準確的答案。 – Leonidas199x

+0

變異https://stackoverflow.com/questions/19432913/select-info-from-table-where-row-has-max-date/19433107#19433107我相信 – Twelfth

回答

0

這聽起來像是你想爲每一種類型的每一行最近一次。如果是這樣的話,這裏有一個方法row_number()

with cte as(
select 
    id 
    ,name 
    ,surname 
    ,timestamp 
    ,type 
    RN = row_number() over (partition by id,type order by timestamp desc)) 

select * 
from cte 
where RN = 1