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
是在它。這裏有什麼想法?
那是什麼'board_id'列第二查詢的'GROUP BY'子句中? –
@LaurenzAlbe我稍微編輯了兩個查詢。我用'board_id'替換了'*'通配符,並給出相同的輸出。這有幫助嗎? – John
請注意,'distinct on'對第一個和第三個查詢沒有影響 –