如何 select 具有最大特定列值的行?
How to select the rows with max certain column value?
我有一个table,有几行两列,是这样的。
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 并输出该行(station_id
和 count
都应该被 select 编辑掉)
select station_id, count(*) count
from bus_lines
group by station_id
order by count desc limit 1;
但我不知道用什么sql语句来select它,如果有几行有最大值。如果你能给我 sql(maybe postgresql) 声明,那就太好了。
从 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
您可能想要使用 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
我有一个table,有几行两列,是这样的。
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 并输出该行(station_id
和 count
都应该被 select 编辑掉)
select station_id, count(*) count
from bus_lines
group by station_id
order by count desc limit 1;
但我不知道用什么sql语句来select它,如果有几行有最大值。如果你能给我 sql(maybe postgresql) 声明,那就太好了。
从 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
您可能想要使用 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