SQL SELECT MAX COUNT

前端 未结 3 1931
萌比男神i
萌比男神i 2021-01-06 09:27

I have three columns in a table: id, streetname, count. To some ids is more than one streetname assinged. Count tells how often the respective street is assigned to the id.

相关标签:
3条回答
  • 2021-01-06 10:16

    I don't think it's the right way to have not unique column name 'id' but your problem should've been solved by this query:

    SELECT id, streetname FROM table ORDER BY count DESC
    
    0 讨论(0)
  • 2021-01-06 10:27

    Try this

    SELECT T1.id, T1.streetname FROM TableName T1
    INNER JOIN 
    (
    SELECT id, MAX(count) maxcnt FROM TableName
    GROUP BY id
    ) T2 
    ON T1.id= T2.id AND T1.count = T2.maxcnt
    

    SQL FIDDLE DEMO

    0 讨论(0)
  • 2021-01-06 10:31

    You did not specify what database you are using but you should be able to use the following:

    select t1.id, t1.streetname, t1.count
    from yourtable t1
    inner join
    (
      select id, max(count) max_count
      from yourtable
      group by id
    ) t2
      on t1.id = t2.id
      and t1.count = t2.max_count
    

    See SQL Fiddle with Demo. Note, you will have to escape the count column name using backticks for MySQL or whatever character your database uses to escape reserved words. My suggestion would be to avoid using reserved words for column and table names.

    0 讨论(0)
提交回复
热议问题