复合聚合查询

时间:2014-09-08 12:20:43

标签: sql postgresql

create temp table tokens (
    id serial not null,
    name text not null,
    locale text not null,
    CONSTRAINT tokens_pkey PRIMARY KEY (id)
);
insert into tokens(name, locale) values 
('e47dd0440c923a77915791ffab7346f4', 'en_US'),
('e47dd0440c923a77915791ffab7346f4', 'en_US'),
('e47dd0440c923a77915791ffab7346f4', 'en_US'),
('e47dd0440c923a77915791ffab7346f4', 'en_US'),
('e47dd0440c923a77915791ffab7346f4', 'en_US'),
('e47dd0440c923a77915791ffab7346f4', 'en_GB'),
('e47dd0440c923a77915791ffab7346f4', 'en_AU'),
('8156773b9da51b7cffb4a1af1a326464', 'de_DE'),
('8156773b9da51b7cffb4a1af1a326464', 'de_DE'),
('8156773b9da51b7cffb4a1af1a326464', 'de_DE'),
('8156773b9da51b7cffb4a1af1a326464', 'de_AT')

select 
    max(cnt) max, name, locale
from (
    select count(id) cnt, name, locale
    from tokens
    group by name, 
    locale
) q
group by
    name, 
    locale
order by 
    max(cnt) desc, 
    name, 
    locale

/*
Result:
max;name;locale
5;e47dd0440c923a77915791ffab7346f4;en_US
3;8156773b9da51b7cffb4a1af1a326464;de_DE
1;8156773b9da51b7cffb4a1af1a326464;de_AT
1;e47dd0440c923a77915791ffab7346f4;en_AU
1;e47dd0440c923a77915791ffab7346f4;en_GB

Expected result:
max;name;locale
5;e47dd0440c923a77915791ffab7346f4;en_US
3;8156773b9da51b7cffb4a1af1a326464;de_DE
*/

我需要具有最大计数的令牌和区域设置,但问题是如果我按区域设置分组我得到错误的结果

Fiddle

2 个答案:

答案 0 :(得分:3)

select cnt, name, locale from (
    select 
        cnt, name, locale,
        row_number() over (partition by name order by cnt desc) rn
    from (
        select count(id) cnt, name, locale
        from tokens
        group by name, 
        locale
    ) t1
) q where rn = 1 order by cnt desc

http://sqlfiddle.com/#!15/33b36/5

答案 1 :(得分:0)

如果您只想要一行,请使用LIMIT

    select count(id) cnt, name, locale
    from tokens
    group by name, locale
    order by count(id) desc
    LIMIT 1