结合三个非常相似的查询? (Postgres的)

时间:2016-09-27 14:23:54

标签: postgresql

所以我有三个问题。我试图将它们全部合并到一个查询中。他们在这里输出:

查询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的{​​{1}}子句。这里有什么想法吗?

1 个答案:

答案 0 :(得分: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