SQL - SELECT MAX() and accompanying field

后端 未结 4 627
终归单人心
终归单人心 2020-12-31 23:41

What I have is basically a problem which is easily solved with multiple tables, but I have only a single table to do it.

Consider the following database table

<
相关标签:
4条回答
  • 2021-01-01 00:03

    I think I have a solution that's different from the ones already proposed:

    select *
    from foo
    where id = (
      select id
      from foo F
      where F.bar = foo.bar
      order by F.baz
      limit 1
    )
    

    This gives you all the foo records that have the greatest baz compared to other foo records with the same bar.

    0 讨论(0)
  • 2021-01-01 00:05

    If you're on SQL Server 2005 or higher,

    SELECT  UserID, UserName, EmailAddress, Source
    FROM    (SELECT UserID, UserName, EmailAddress, Source,
                    ROW_NUMBER() OVER (PARTITION BY UserID
                                       ORDER BY EmailAddress DESC) 
                        AS RowNumber
             FROM   MyTable) AS a
    WHERE   a.RowNumber = 1
    

    Of course there are ways to do the same task without the (SQL-Standard) ranking functions such as ROW_NUMBER, which SQL Server implemented only since 2005 -- including nested dependent queries and self left joins with an ON including a '>' and a WHERE ... IS NULL trick -- but the ranking functions make for code that's readable and (in theory) well optimizable by the SQL Server Engine.

    Edit: this article is a nice tutorial on ranking, but it uses RANK in the examples instead of ROW_NUMBER (or the other ranking function, DENSE_RANK) -- the distinction matters when there are "ties" among grouped rows in the same partition according to the ordering criteria. this post does a good job explaining the difference.

    0 讨论(0)
  • 2021-01-01 00:07
    select distinct * from table t1
    where EmailAddress = 
    (select max(EmailAddress) from table t2
    where t1.userId = t2.userId)
    
    0 讨论(0)
  • 2021-01-01 00:08
    select distinct
         *  
    from    
       SomeTable a
    inner join (
      select max(emailAddress), userId
      from
         SomeTable 
      group by 
         userId
    ) b on a.emailAddress = b.emailAddress and a.userId = b.userId
    
    0 讨论(0)
提交回复
热议问题