我之前设法做到了但是不记得怎么也找不到答案: 我正在尝试在数据库中查询sum()并将结果传播到2行 例如sum(男性)为'男性',sum(女性)为'女性',sum(男性+女性)为'总' 新行 总和(年龄> 45岁的男性),总和(年龄> 45岁的女性),总和(男性+女性超过45岁)为“总计” 我确信这很简单但很烦我,请帮忙
答案 0 :(得分:1)
尝试类似......
SELECT SUM(CASE WHEN Age <=45 THEN MEN ELSE 0 END) AS Men
,SUM(CASE WHEN Age <=45 THEN WOMEN ELSE 0 END) AS Women
,SUM(CASE WHEN Age <=45 THEN Men+WOMEN ELSE 0 END) AS Total
,'45 or Under' AS AgeGroup
FROM Table
UNION ALL
SELECT SUM(CASE WHEN Age > 45 THEN MEN ELSE 0 END) AS Men
,SUM(CASE WHEN Age > 45 THEN WOMEN ELSE 0 END) AS Women
,SUM(CASE WHEN Age > 45 THEN Men+WOMEN ELSE 0 END) AS Total
,'above 45' AS AgeGroup
FROM Table
或者你可以做一些......
SELECT SUM(MEN) AS Men
,SUM(WOMEN) AS Women
,SUM(Men+WOMEN) AS Total
,'45 or Under' AS AgeGroup
FROM Table WHERE Age <= 45
UNION ALL
SELECT SUM(MEN) AS Men
,SUM(WOMEN) AS Women
,SUM(Men+WOMEN) AS Total
,'45 or Under' AS AgeGroup
FROM Table WHERE Age > 45