使用cross apply()
使用top with ties
和row_number()
select top 1 with ties *
from t
order by row_number() over (partition by Name order by date desc, id desc)
:使用
select distinct
x.id
, t.Name
, [Date] = convert(char(10),x.[Date],120)
, x.DepositAmount
from t
cross apply (
select top 1 i.id, i.Date, i.DepositAmount
from t i
where t.Name = i.Name
order by i.Date desc, i.id desc
) x
一個common table expression與row_number()
;with cte as (
select *
, rn = row_number() over (partition by Name order by date desc, id desc)
from t
)
select
t.id
, t.Name
, [Date] = convert(char(10),t.[Date],120)
, t.DepositAmount
from cte t
where rn = 1
使用inner join
得到max(id)
如果同一個名稱not exists()
select
t.id
, t.Name
, [Date] = convert(char(10),t.[Date],120)
, t.DepositAmount
from t
inner join (
select
id = max(i.id)
, i.Name
from t i
where not exists (
select 1
from t e
where e.Name = i.Name
and e.Date > i.Date
)
group by i.Name
) m
on t.Name = m.Name
and t.Id = m.Id
rextester演示更大的日期:http://rextester.com/GNQ24777
我喜歡這種方法。沒有額外/不需要的字段+1 –