繁体   English   中英

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

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

我有一个有几行和两列的表格,它是这样的。

 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

我想要 select 具有最大count数值的行。 如果只有一行具有最大值,我知道我可以 select 和 output 行(应该选择station_idcount

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

但是我不知道如果有几行具有最大值,我不知道使用什么 sql 语句到 select 它。 如果你能给我提供 sql(也许是 postgresql)语句,那就太好了。

您可能想使用 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

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