SQL查询以获得行总计

时间:2016-03-07 13:51:47

标签: sql-server

我正在使用SQL Server 2008.我想获得表的行总计,并希望合并总列的2个字符串列名。我有下表数据

Region Test  taken  Nottaken 
India  AA    1      0 
UK     AS    3      4 
US     AF    1      1 

我想要结果集如下

Region Test  taken  Nottaken Total 
India  AA    1      0        1 
UK     AS    3      4        7 
US     AF    1      1        2 
total        5      5        10

如何编写查询?

2 个答案:

答案 0 :(得分:0)

您可以使用UNION来添加总行,如下所示:

SELECT * FROM(
    SELECT region,test,taken,nottaken,taken+nottaken as total
    FROM YourTable
    UNION 
    SELECT 'region','test',sum(taken),sum(nottaken) ,sum(nottaken+taken)
    FROM YourTable)
ORDER BY CASE WHEN region <> 'region' then 0 else 1 end 

答案 1 :(得分:0)

只需在select语句中进行数学运算,将两列一起添加......

Select Region, Test, Taken, NotTaken, Taken+notTaken as total
from table