I've written two SQL statements:
SELECT Count(*) AS table1Count FROM table1 WHERE foo=1;
SELECT Count(*) AS table2Count FROM table2 WHERE bar=2;
Both statements return the data I want, but I would like to know how to return a sing开发者_运维问答le table with two cells: table1Count and table2Count from a single query.
How do I do construct the query?
SELECT (SELECT Count(*) AS table1Count FROM table1 WHERE foo=1) AS table1Count,
(SELECT Count(*) AS table2Count FROM table2 WHERE bar=2) AS table2Count;
Gives something like:
table1count | table2count
-------------+-------------
4 | 6
(1 row)
With UNION ALL
:
SELECT 'Table1' AS "Table", Count(*) As "Count" FROM table1 WHERE foo=1
UNION ALL
SELECT 'Table2' AS "Table", Count(*) As "Count" FROM table2 WHERE bar=2;
Will produce:
Table | Count
---------------
Table1 | 1
Table2 | 2
精彩评论