Postgresql嵌套选择最大值(sum())
我的问题是:Postgresql嵌套选择最大值(sum()),postgresql,nested,aggregate,Postgresql,Nested,Aggregate,我的问题是: select table.attribute, count(table.attribute) AS cnt from table group by table.attribute order by cnt desc; 输出类似于: attribute | cnt -----------+----- A | 2 B | 2 G | 1 F | 1 但我只想要最大值(A和B) 您可以使用的功
select table.attribute, count(table.attribute) AS cnt from table
group by table.attribute
order by cnt desc;
输出类似于:
attribute | cnt
-----------+-----
A | 2
B | 2
G | 1
F | 1
但我只想要最大值(A和B) 您可以使用的功能来实现这一点:
WITH count_values
AS (SELECT table.attribute,
Count(table.attribute) AS cnt
FROM table
GROUP BY table.attribute),
max_values
AS (SELECT Max(cnt) AS max_cnt
FROM (SELECT cnt
FROM count_values) sub)
SELECT *
FROM count_values cv
JOIN max_values mv
ON mv.max_cnt = cv.cnt;
你可以使用下面的等级
with cte as (
select *, Rank() over(order by cnt desc) as rnk from yourattribute
) select * from cte where rnk = 1
您可以通过一个嵌套级别执行此操作:
select attribute,
cnt
from (
select attribute,
count(*) AS cnt,
max(count(*)) over () as max_cnt
from t
group by attribute
) t
where cnt = max_cnt;
为你和@klin干杯我找到的所有资源都不适合我!很高兴帮助你@Haveedguy