如何计算SQL中的最高频繁值

时间:2020-10-16 11:35:33

标签: sql postgresql count aggregate-functions greatest-n-per-group

我有一个包含三列的表:货币,使用该货币进行交易的交易所,日期

Currency  Exchange Date
USD       NewYork  01/12/20
USD       NewYork  01/11/20
USD       NewYork  01/10/20
USD       Montreal 01/10/20
CAD       Montreal 01/07/20
CAD       Montreal 01/06/20
CAD       Beijing  01/06/20

我需要回答以下问题:哪种交易所是该特定货币的领导者。

这意味着对于给定的货币,计算要交换的记录数量 只返回最大值 换句话说,查询结果应该类似于

Currency Exchange Frequency 
USD      NewYork  3
CAD      Montreal 2 

4 个答案:

答案 0 :(得分:2)

如果要在聚合查询中使用最常见的行,请使用窗口函数:

select ce.*
from (select currency, exchange, count(*) as cnt,
             rank() over (partition by currency order by count(*) desc) as seqnum
      from t
      group by currency, exchange
     ) ce
where seqnum = 1;

注意:如果发生平局,则返回所有最大值。如果只需要一个,则使用row_number()代替rank()

编辑:

在Postgres(我回答后添加)中,您可以使用distinct on

select distinct on (currency) exchange, count(*) as cnt
from t
group by currency, exchange
order by currency, count(*) desc;

请注意,如果有关系,这不会返回重复项。

答案 1 :(得分:2)

您可以使用窗口功能:

select *
from (
    select currency, exchange, count(*) frequency,
        rank() over(partition by currency order by count(*) desc) rn
    from mytable
    group by currency, exchange
) t
where rn = 1

答案 2 :(得分:2)

您可以在场景中使用distinct on。只需通过分组计数 currencyexchange并按currencycount降序排列。 因此查询将如下所示:

select
distinct on (currency)
currency,
exchange,
count(*)
from table1
group by 1,2
order by 1,3 desc

答案 3 :(得分:1)

具有first_value()max()窗口功能:

select distinct currency,
       first_value(exchange) over (partition by currency order by count(*) desc) exchange,
       max(count(*)) over (partition by currency) frequency
from tablename
group by currency, exchange

请参见demo
结果:

> currency | exchange    | frequency
> :------- | :---------- | --------:
> CAD      | Montreal    |         2
> USD      | NewYork     |         3