PostgreSQL-filter类别是最常见的值

时间:2017-06-01 17:13:07

标签: postgresql mode

我试图将mode()或most_common_vals()函数用作子查询条件。

SELECT user_id, COUNT(request_id) AS total
FROM requests
WHERE category = (SELECT mode(category) AS modal_category FROM requests)
GROUP BY user_id
ORDER BY total DESC
LIMIT 5;

但是,我继续收到有关两个功能都不存在的错误。

1 个答案:

答案 0 :(得分:0)

如果我正确理解,你需要这样的东西:

with requests  (user_id,  request_id, category) as (
select 1, 111, 'A' union all
select 1, 111, 'A' union all
select 2, 111, 'A' union all
select 2, 111, 'B' union all
select 1, 111, 'B' union all
select 3, 111, 'B' union all
select 1, 111, 'B' union all
select 1, 111, 'C'  
 )

-- Below is actual query: 

select user_id, COUNT(request_id)  AS total
from (
    select t.*, rank() over(order by cnt desc) as rnk from (
        select requests.*, count(*) over(partition by category) as cnt from requests
    ) t
) tt 
where rnk = 1
group by user_id
order by total desc
limit 5

此处user_idCOUNT(request_id)仅针对'B'类别计算,因为在此示例中最常见。

另请注意,如果有多个最常见的类别,此查询会生成所有这些类别的结果。