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?
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;
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.