,你可以簡單地使用
WITH TableCount AS
(
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
和使用後下面的查詢
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
如果您正在使用MySql
您可以使用臨時表來執行類似的CTE
CREATE TEMPORARY TABLE IF NOT EXISTS TableCount AS (
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
然後你就可以使用上面的查詢
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
創建表時,您可以使用TEMPORARY關鍵詞。 TEMPORARY 表僅對當前會話可見,並在會話關閉時自動丟棄 。這意味着兩個不同的會話可以使用相同的臨時表名稱,而不會與 相互衝突,或者與同名的現有非臨時表 衝突。 (現有表將隱藏,直到刪除臨時表 。)要創建臨時表,您必須具有CREATE TEMPORARY TABLES特權。
通過使用臨時表的概念就可以實現公用表表達式類型的功能在MySQL
這些人大概是不朽的? – Strawberry