0

I need to query three values from two tables. the first two values are queried as follows:

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

the third value downCount should be count - upCount. can this operation be done by psql and returned as downCount?

2 Answers 2

1

One option would be to simply repeat the subqueries:

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;

You could also use a CTE to compute the original two subqueries first:

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a subquery or move the subqueries to the FROM clause. I would suggest the latter:

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.