Sql 向列中添加一行,该行包含该列中的值之和

Sql 向列中添加一行,该行包含该列中的值之和,sql,sql-server,Sql,Sql Server,每当大陆与国家不同时,我希望我的代码在“大陆”列中返回空格,并在表的末尾显示每个大陆45岁以下的人口总数、每个大陆45岁以上的人口总数以及每个大陆的居民总数,如下面的示例所示: Continent | Country | Bellow 45 yo | Above 45 yo | Total Habitants ------------------------------------------------------------------- Europe | Europe |

每当大陆与国家不同时,我希望我的代码在“大陆”列中返回空格,并在表的末尾显示每个大陆45岁以下的人口总数、每个大陆45岁以上的人口总数以及每个大陆的居民总数,如下面的示例所示:

Continent | Country  | Bellow 45 yo | Above 45 yo | Total Habitants
-------------------------------------------------------------------
Europe    | Europe   |      1       |      1      |       2 
          | England  |      0       |      1      |       1 
          | Portugal |      1       |      0      |       1 
NA        | NA       |      2       |      1      |       3 
          | Canada   |      0       |      1      |       1 
          | USA      |      2       |      0      |       2 
Total     | Total    |      3       |      2      |       5 
我在试这个密码

SELECT t1.continent as Continent,
       COALESCE(t1.country, t1.continent) as Country,
       COUNT(CASE WHEN t2.age < 45 THEN 1 END) AS under_45,
       COUNT(CASE WHEN t2.age > 45 THEN 1 END) AS over_45,
       COUNT(CASE WHEN t2.age > 45 or t2.age > 45 THEN 1 END) AS Total
FROM t1 JOIN
     t2
     ON t2.id = t1.id
GROUP BY GROUPING SETS ( (t1.continent, t1.country), (t1.continent) )
ORDER BY t1.continent,
         (CASE WHEN t1.country IS NULL THEN 1 ELSE 2 END),
         t1.country;
原始数据为:

T1:                                   T2:
ID | Country  | Continent             ID | Name     | Age  | CountryID           
--------------------------            ---------------------------------
1  | England  | Europe                1  | Mary     | 67   |     1
2  | USA      | NA                    2  | Anthoine | 34   |     2
3  | Portugal | Europe                3  | Jorge    | 19   |     3
4  | Canada   | NA                    4  | Bella    | 46   |     4
                                      5  | Ana      | 26   |     2

嗯。我想你想要:

SELECT (CASE WHEN t1.Country IS NULL THEN t1.continent END) as Continent,       
       COALESCE(t1.country, t1.continent) as Country,
. . . 

但是为什么不把它们合并成一个专栏呢?现在你的
国家是什么?

第一部分的代码运行得很好。但是现在我需要在表的末尾添加一行,显示上面每个值的总和,比如excel中的
=sum(A1:A20)
SELECT (CASE WHEN t1.Country IS NULL THEN t1.continent END) as Continent,       
       COALESCE(t1.country, t1.continent) as Country,
. . .