2016-09-27 47 views
1

所以我有三个查询。我试图将它们全部合并为一个查询。这里它们与它们的输出:结合三个非常相似的查询? (Postgres)

查询1:

SELECT distinct on (name) name, count(distinct board_id) 
FROM tablea 
INNER JOIN table_b on tablea.id = table_b.id 
GROUP BY name 
ORDER BY name ASC 

输出:

A | 15 
B | 26 
C | 24 
D | 11 
E | 31 
F | 32 
G | 16 

问题2:

SELECT distinct on (name) name, count(board_id) as total 
FROM tablea 
INNER JOIN table_b on tablea.id = table_b.id 
GROUP BY 1, board_id 
ORDER BY name, total DESC 

输出:

A | 435 
B | 246 
C | 611 
D | 121 
E | 436 
F | 723 
G | 293 

最后,最后查询:

SELECT distinct on (name) name, count(board_id) as total 
FROM tablea 
INNER JOIN table_b on tablea.id = table_b.id 
GROUP BY 1 
ORDER BY name, total DESC 

输出:

A | 14667 
B | 65123 
C | 87426 
D | 55198 
E | 80612 
F | 31485 
G | 43392 

是否有可能进行格式化是这样的:

A | 15 | 435 | 14667 
B | 26 | 246 | 65123 
C | 24 | 611 | 87426 
D | 11 | 121 | 55198 
E | 31 | 436 | 80612 
F | 32 | 723 | 31485 
G | 16 | 293 | 43392 

编辑:

随着@ Clodoaldo Neto的帮助,我将第一个和第三个查询与这个结合起来:

SELECT name, count(distinct board_id), count(board_id) as total 
FROM tablea 
INNER JOIN table_b on tablea.id = table_b.id 
GROUP BY 1 
ORDER BY description ASC 

阻止我的第二个查询用这个新组合的唯一的事情是GROUP BY条款需要board_id是在它。这里有什么想法?

+0

那是什么'board_id'列第二查询的'GROUP BY'子句中? –

+0

@LaurenzAlbe我稍微编辑了两个查询。我用'board_id'替换了'*'通配符,并给出相同的输出。这有帮助吗? – John

+1

请注意,'distinct on'对第一个和第三个查询没有影响 –

回答

1

如果没有测试数据,这很难找到正确的答案。但这里是我的尝试:

with s as (
    select name, grouping(name, board_id) as grp, 
     count(distinct board_id) as dist_total, 
     count(*) as name_total, 
     count(*) as name_board_total 
    from 
     tablea 
     inner join 
     table_b on tablea.id = table_b.id 
    group by grouping sets ((name), (name, board_id)) 
) 
select name, dist_total, name_total, name_board_total 
from 
    (
     select name, dist_total, name_total 
     from s 
     where grp = 1 
    ) r 
    inner join 
    (
     select name, max(name_board_total) as name_board_total 
     from s 
     where grp = 0 
     group by name 
    ) q using (name) 
order by name 

https://www.postgresql.org/docs/current/static/queries-table-expressions.html#QUERIES-GROUPING-SETS