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'对第一个和第三个查询没有影响 –