我刚开始学习如何编码。
我想知道如何在一个查询中组合多个SELECT语句。

SELECT count(*) AS "SENT" FROM message_items WHERE status = 'SENT';

SELECT count(*)  AS "NOT SENT" FROM message_items WHERE status = 'NOT SENT';

SELECT count(*) AS "INVALID NUMBER" FROM message_items WHERE status = 'INVALID NUMBER';

最佳答案

使用条件聚合:

SELECT
    COUNT(*) FILTER (WHERE status = 'SENT') AS "SENT",
    COUNT(*) FILTER (WHERE status = 'NOT SET') AS "NOT SENT",
    COUNT(*) FILTER (WHERE status = 'INVALID NUMBER') AS "INVALID NUMBER"
FROM message_items;

如果您想生成整个表的计数,那么上面的方法是合适的。如果您想为其他列生成计数,那么只需将该列添加到上面的select子句中,然后使用GROUP BY按该列聚合。

关于postgresql - 如何在PostgreSQL中合并多个选择语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58501245/

10-10 04:17