SQL - Select unique rows from a group of results

前端 未结 5 1158
时光说笑
时光说笑 2021-01-25 14:44

I have wrecked my brain on this problem for quite some time. I\'ve also reviewed other questions but was unsuccessful.

The problem I have is, I have a list of results/t

5条回答
  •  渐次进展
    2021-01-25 15:31

    TSQL:

    declare @R table
    (
    Registration varchar(16),
    ID int,
    Date datetime,
    UnitType varchar(16)
    )
    
    insert into @R values ('A','1','20090824','A')
    insert into @R values ('A','2','20090825','B')
    
    select R.Registration,R.ID,R.UnitType,R.Date from @R R
    inner join
    (select Registration,Max(Date) as Date from @R group by Registration) M
    on R.Registration = M.Registration and R.Date = M.Date
    

    This can be inefficient if you have thousands of rows in your table depending upon how the query is executed (i.e. if it is a rowscan and then a select per row).

提交回复
热议问题