简体   繁体   English

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

[英]How to add a total row at the end of the table in t-sql?

I need to add a row of sums as the last row of the table. 我需要添加一总和作为表的最后一行。 For example: 例如:

   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

How can I do this? 我怎样才能做到这一点? (T-SQL) (T-SQL)

You can use union all : 您可以使用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;

However, count(*) will give you no of rows available in table, if the book_name has null value also, then you need count(book_name) instead of count(*) . 但是, count(*)不会提供表中可用no of rows ,如果book_name也具有null值,那么您需要count(book_name)而不是count(*)

Try with ROLLUP 尝试使用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

I find that grouping sets is much more flexible than rollup . 我发现grouping setsrollup更灵活。 I would write this as: 我可以这样写:

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), () );

Strictly speaking, the GROUPING function with a CASE is better than COALESCE() . 严格来说,带有CASEGROUPING函数比COALESCE()更好。 However, NULL values on the grouping keys is quite rare. 但是,分组键上的NULL值很少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM