MySQL: Select N rows, but with only unique values in one column

前端 未结 5 802
醉梦人生
醉梦人生 2020-12-23 10:07

Given this data set:

ID  Name            City            Birthyear
1   Egon Spengler   New York        1957
2   Mac Taylor      New York        1955
3   Sara         


        
5条回答
  •  庸人自扰
    2020-12-23 10:41

    Not pretty but should work also with multiple people with the same dob:

    Test data:

    select id, name, city, dob 
    into people
    from
    (select 1 id,'Egon Spengler' name, 'New York' city , 1957 dob
    union all select 2, 'Mac Taylor','New York', 1955
    union all select 3, 'Sarah Connor','Los Angeles', 1959
    union all select 4, 'Jean-Luc Picard','La Barre', 2305
    union all select 5, 'Ellen Ripley','Nostromo', 2092
    union all select 6, 'James T. Kirk','Riverside', 2233
    union all select 7, 'Henry Jones','Chicago', 1899
    union all select 8, 'Blah','New York', 1955) a
    

    Query:

    select 
        * 
    from 
        people p
        left join people p1
        ON 
            p.city = p1.city
            and (p.dob > p1.dob and p.id <> p1.id)
            or (p.dob = p1.dob and p.id > p1.id)
    where
        p1.id is null
    order by 
        p.dob
    

提交回复
热议问题