简体   繁体   中英

SQL select first of possible duplicates and also include singles ordered by date

I have a table of Sign Ups for an event such as

 name  | signup_date
--------------------
Maria  | 2016-02-24
Maria  | 2016-02-24
Maria  | 2016-02-24
David  | 2016-02-25
David  | 2016-02-25
George | 2016-02-26

There's the potential that someone may sign up more than once, and this is expected behavior.

I need to be able to select and order so that I can get all the unique records with all the duplicates after. Basically, if you signed up multiple times I want to go through all the names in a unique fashion first before getting to duplicates. And I can't figure out how to do this in one query.

Expected Results should look like this:

 name  | signup_date
--------------------
Maria  | 2016-02-24 <- maria's first
David  | 2016-02-25 <- david's first
George | 2016-02-26 
Maria  | 2016-02-24 <- maria's 2nd
David  | 2016-02-25 <- david's 2nd
Maria  | 2016-02-24 <- maria's 3rd

So that both David and George get a chance in the list, ordered by sign up date, before Maria has her 2nd or 3rd option, even though she signed up for all 3 on the same day.

You can do this by enumerating the signups (using variables in the case of MySQL) and then ordering on that field:

select s.*
from (select s.*,
             (@rn := if(@name = name, @rn + 1,
                        if(@name := name, 1, 1)
                       )
             ) as rn
      from signups s cross join
           (select @rn := 0, @name := '') params
      order by name, signup_date
     ) s
order by rn, date;

why not just order by name, signup_date?

select * from [table] order by name , signup_date.

You can also order by the table primary key desc. This way you can see all of Maria's entries, based on which was submitted.

使用AS(SELECT名称,SignUp_date,ROW_NUMBER()OVER(按名称排序,按SignUp_date DESC排序)AS Ranky从#tmp选择AS.NAME,a.SignUp_date从ORDER BY排序,SignUp_date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM