SQL - Select unique rows from a group of results

前端 未结 5 1119
时光说笑
时光说笑 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:27

    This should work in MySQL:

    SELECT registration, id, date, unittype FROM 
      (SELECT registration AS temp_reg, MAX(date) as temp_date 
      FROM table_name GROUP BY registration) AS temp_table
    WHERE registration=temp_reg and date=temp_date
    

    The idea is to use a subquery in a FROM clause which throws up a single row containing the correct date and registration (the fields subjected to a group); then use the correct date and registration in a WHERE clause to fetch the other fields of the same row.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-25 15:31

    In PostgreSQL, and assuming your data is indexed so that a sort isn't needed (or there are so few rows you don't mind a sort):

    select distinct on (registration), * from whatever order by registration,"date" desc;
    

    Taking each row in registration and descending date order, you will get the latest date for each registration first. DISTINCT throws away the duplicate registrations that follow.

    0 讨论(0)
  • 2021-01-25 15:36
    select registration,ID,date,unittype
    from your_table
    where (registration, date) IN (select registration,max(date)
                                from your_table
                                group by registration)    
    
    0 讨论(0)
  • 2021-01-25 15:38

    You want embedded queries, which not all SQLs support. In t-sql you'd have something like

    select  r.registration, r.recent, t.id, t.unittype
    from    ( 
        select  registration, max([date]) recent
        from    @tmp 
        group by 
            registration
        ) r
    left outer join 
        @tmp t 
    on  r.recent = t.[date]
    and r.registration = t.registration 
    
    0 讨论(0)
提交回复
热议问题