简体   繁体   English

如何 select 具有最大特定列值的行?

[英]How to select the rows with max certain column value?

I have a table with several rows and two columns, it is like this.我有一个有几行和两列的表格,它是这样的。

 station_id | count
------------+-------
        184 |     7
         87 |    31
         71 |    29
         68 |     7
         51 |    65
        146 |    22
         80 |    37
         70 |    18
         52 |    12
        132 |    21
         84 |    65
        176 |    29
         92 |    21
        101 |    28
         69 |     4
        180 |    32
         97 |    32
        108 |     9
        156 |    50
         59 |    10
        135 |    24
         65 |    20
        127 |    44
        124 |    20
         98 |    28
        178 |    65

I want to select the rows with max count value.我想要 select 具有最大count数值的行。 If there is only one row with the max value, I know I can select and output the row ( station_id and count both should be selected out) by如果只有一行具有最大值,我知道我可以 select 和 output 行(应该选择station_idcount

select station_id, count(*) count
from bus_lines
group by station_id
order by count desc limit 1;

But I don't know use what sql statement to select it if there is several rows with the max value.但是我不知道如果有几行具有最大值,我不知道使用什么 sql 语句到 select 它。 It would be great if you can offer me the sql(maybe postgresql) statement.如果你能给我提供 sql(也许是 postgresql)语句,那就太好了。

You might want to use RANK() or DENSE_RANK()您可能想使用 RANK() 或 DENSE_RANK()

SELECT * FROM (select station_id, count(*) count,
dense_rank() over(order by count desc) as count_rank
from bus_lines
GROUP BY station_id
ORDER BY count_rank
) t

Switch from LIMIT to FETCH FIRST 1 ROW WITH TIES to include all rows having the max count:LIMIT切换到FETCH FIRST 1 ROW WITH TIES以包括具有最大计数的所有行:

select station_id, count(*) count
from bus_lines
group by station_id
order by count desc FETCH FIRST 1 ROW WITH TIES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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