SQL: Return only first occurrence

前端 未结 5 1835
慢半拍i
慢半拍i 2021-02-19 11:24

I seldomly use SQL and I cannot find anything similar in my archive so I\'m asking this simple query question: I need a query which one returns personID and onl

相关标签:
5条回答
  • 2021-02-19 11:59

    for PostgreSQL there is DISTINCT ON

    0 讨论(0)
  • 2021-02-19 12:05

    You need to order by seen time not by seen id:

    PARTITION BY seenID ORDER BY seenTime
    
    0 讨论(0)
  • 2021-02-19 12:09

    You're making it way too difficult:

    select personID, min(seenTime)
    from personAttendances
    group by personID
    
    0 讨论(0)
  • 2021-02-19 12:18

    Add this to your SQL:

    and where not exists
        (select 1 from personAttendances t2 
        where t.personID=t2.personID 
        and t2.seenID < t.seenID)
    
    0 讨论(0)
  • If your seenTime increases as seenID increases:

    select personID, min(seenTime) as seenTime
    from personAttendances
    group by personID
    

    Update for another case:

    If this is not the case, and you really want the seenTime that corresponds with the minimum seenID (assuming seenID is unique):

    select a.personID, a.seenTime
    from personAttendances as a
        join (
            -- Get the min seenID for each personID
            select personID, min(seenID) as seenID
            from personAttendances
            group by personID
        ) as b on a.personID = b.personID
    where a.seenID = b.seenID
    
    0 讨论(0)
提交回复
热议问题