查询以根据每个组中的最新日期选择值。如果相同日期,则默认为最大ID

时间:2017-06-12 21:03:36

标签: sql sql-server

我在表格中有以下数据。

ID  Name    Date        DepositAmount

1   John    2012-01-04  70790.90
2   John    2012-01-04  73450.13
3   Samuel  2010-06-17  3700.00
4   Karen   2017-06-01  2210.00
5   Karen   2013-06-12  1300.00

对于每个人,我必须选择最新的存款金额。如果两个存款都发生在同一天,那么应该选择ID最高的记录。

所以,结果看起来像

2   John    2012-01-04  73450.13
3   Samuel  2010-06-17  3700.00
4   Karen   2017-06-01  2210.00

尝试:

我试图通过使用游标来解决这个问题,但代码看起来过于复杂和不必要。

1 个答案:

答案 0 :(得分:2)

使用top with tiesrow_number()

select top 1 with ties *
from t
order by row_number() over (partition by Name order by date desc, id desc)

使用cross apply()

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