2017-10-17 58 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