2016-09-27 46 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