如何在t-sql的表末尾添加总行?

时间:2018-10-12 09:14:31

标签: sql sql-server tsql

我需要在表的最后一行添加一行求和。例如:

   book_name   |   some_row1   |   some_row2   |   sum   
---------------+---------------+---------------+----------
    book1      |   some_data11 |   some_data12 |   100
    book2      |   some_data21 |   some_data22 |   300
    book3      |   some_data31 |   some_data32 |   500
 total_books=3 |   NULL        |   NULL        |   900

我该怎么做? (T-SQL)

3 个答案:

答案 0 :(得分:2)

您可以使用union all

select book_name, some_row1, some_row2, sum 
from table t
union all
select cast(count(*) as varchar(255)), null, null, sum(sum)
from table t;

但是,count(*)将为您提供表中的no of rows,如果book_name也具有null值,则您需要count(book_name)而不是{{ 1}}。

答案 1 :(得分:2)

尝试使用ROLLUP

SELECT  CASE 
            WHEN (GROUPING([book_name]) = 1) THEN 'total_books'
            ELSE [book_name] END AS [book_name],some_row1, some_row2
        ,SUM(]sum]) as Total_Sales
From    Before
GROUP BY
        [book_name] WITH ROLLUP

答案 2 :(得分:0)

我发现grouping setsrollup更灵活。我将其写为:

select coalesce(book_name,
                replace('total_books=@x', '@x', count(*))
               ) as book_name,
       col2, col3, sum(whatever)
from t
group by grouping sets ( (book_name), () );

严格来说,带有GROUPING的{​​{1}}函数比CASE更好。但是,分组键上的COALESCE()值非常少。