簡體   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