输出SQL中具有最大字段的行

问题描述 投票:-2回答:4

这是我拥有的数据表的一部分:

enter image description here

我如何查询该表以返回每个城市,仅返回具有MAX(turnover)的行,例如,对于Berlin,仅应返回具有21.574,00的行。

sql database postgresql max aggregate
4个回答
-1
投票

在Postgres上,您应该在此处使用DISTINCT ON

SELECT DISTINCT ON (city) city, store, dow, turnover
FROM yourTable
ORDER BY city, turnover DESC;

0
投票

要为每个max(turnover)生成city,请使用group by

select city, max(turnover) turnover
from tableA
group by city

0
投票

使用SELECT city, max(turnover) FROM table GROUP BY city这将返回城市及其最大营业额


0
投票

如果您需要所有达到最大值的列,则可以使用像这样的窗口函数...

with your_fake_table as (
select * from (
values (1, 'Berlin' , 1 , 21000),
(1, 'Berlin' , 2 , 10000),
(1, 'Berlin' , 3 , 5000),
(2, 'Essen' , 31 , 10000),
(2, 'Essen' , 5 , 11000)
) as V (store, city, down, turnover))

select store, city, down, turnover
from (
select 
store,
city,
FIRST_VALUE(down) over (partition by city order by turnover desc) as down,
max(turnover) over (partition by city) as turnover
from your_fake_table
)V
group by store, city, down, turnover

但是如果您不需要向下列,则仅需要城市/商店/最大营业额一个简单的分组会更适合您]

select store, city, max(turnover) turnover
from your_table
group by store, city

请参见带有示例的小提琴演示:

https://dbfiddle.uk/?rdbms=postgres_12&fiddle=e61b775321b4120d87ea11626c09c140

© www.soinside.com 2019 - 2024. All rights reserved.