在PostgreSQL查询中执行数学

时间:2019-06-10 11:01:00

标签: sql postgresql

我需要从两个表中查询三个值。前两个值的查询如下:

SELECT
    (SELECT COUNT(*) FROM table1) AS count,
    (SELECT COUNT(*) FROM table2 WHERE config IS NULL) AS upCount,

第三个值downCount应该为count-upCount。可以通过psql完成此操作并以downCount返回吗?

2 个答案:

答案 0 :(得分:1)

一种选择是简单地重复子查询:

SELECT
    (SELECT COUNT(*) FROM table1) AS count,
    (SELECT COUNT(*) FROM table2 WHERE config IS NULL) AS upCount,
    (SELECT COUNT(*) FROM table1) -
        (SELECT COUNT(*) FROM table2 WHERE config IS NULL) AS downCount;

您还可以使用CTE首先计算原始的两个子查询:

WITH cte AS (
    (SELECT COUNT(*) FROM table1) AS count,
    (SELECT COUNT(*) FROM table2 WHERE config IS NULL) AS upCount
)

SELECT
    count,
    upCount,
    count - upCount AS downCount
FROM cte;

答案 1 :(得分:0)

您可以使用子查询或将子查询移至FROM子句。我建议后者:

SELECT t1.cnt, t2.upcount, (t1.cnt - t2.upcount) as downcount
FROM (SELECT COUNT(*) as cnt FROM table1) t1 CROSS JOIN
     (SELECT COUNT(*) as upcount FROM table2 WHERE config IS NULL) t2;