如何获取resultset的最后一行中的所有列值的和?

时间:2022-11-30 12:41:54

I need to get the sum of all column values of a result set in the last row.
Here is my SQL query.

我需要得到最后一行中结果集的所有列值的和。这是我的SQL查询。

select Master_Code, SUM(Jan), SUM(Feb), SUM(Mar)
from dbo.foobar
WHERE Participating_City = 'foofoo'
GROUP BY Master_Code ORDER BY Master_Code ASC

something like this:

是这样的:

    Master_Code Jan Feb Mar 
    1            4   5   6
    2            5   5   5
    Total        9  10  11

3 个解决方案

#1


11  

Assuming there are no null master_code rows.

假设没有null master_code行。

SELECT ISNULL(Master_code, 'Total') AS Master_Code,
       Jan,
       Feb,
       Mar
FROM (
      SELECT Master_code,
             SUM(Jan) AS Jan,
             SUM(Feb) AS Feb,
             SUM(Mar) AS Mar
      FROM foobar
      WHERE Participating_City = 'foofoo'
      GROUP BY Master_code WITH ROLLUP
     ) AS DT

#2


16  

Make a union where you repeat the same query but without the grouping:

创建一个重复相同查询但没有分组的联合:

select Title, Jan, Feb, Mar
from (
  select Master_Code as Title, SUM(Jan) as Jan, SUM(Feb) as Feb, SUM(Mar) as Mar
  from dbo.foobar
  WHERE Participating_City = 'foofoo'
  GROUP BY Master_Code ORDER BY Master_Code ASC
) x
union all
select 'Total', SUM(Jan) as Jan, SUM(Feb) as Feb, SUM(Mar) as Mar
from dbo.foobar
WHERE Participating_City = 'foofoo'

#3


2  

You can also use Coalesce and With Rollup.

您还可以使用Coalesce和Rollup。

SELECT COALESCE(Master_Code, 'TOTAL') AS MASTER_CODE, SUM(Jan), SUM(Feb), SUM(Mar)
FROM dbo.foobar
WHERE Participating_City = 'foofoo'
GROUP BY Master_Code WITH ROLLUP
ORDER BY Master_Code DESC

#1


11  

Assuming there are no null master_code rows.

假设没有null master_code行。

SELECT ISNULL(Master_code, 'Total') AS Master_Code,
       Jan,
       Feb,
       Mar
FROM (
      SELECT Master_code,
             SUM(Jan) AS Jan,
             SUM(Feb) AS Feb,
             SUM(Mar) AS Mar
      FROM foobar
      WHERE Participating_City = 'foofoo'
      GROUP BY Master_code WITH ROLLUP
     ) AS DT

#2


16  

Make a union where you repeat the same query but without the grouping:

创建一个重复相同查询但没有分组的联合:

select Title, Jan, Feb, Mar
from (
  select Master_Code as Title, SUM(Jan) as Jan, SUM(Feb) as Feb, SUM(Mar) as Mar
  from dbo.foobar
  WHERE Participating_City = 'foofoo'
  GROUP BY Master_Code ORDER BY Master_Code ASC
) x
union all
select 'Total', SUM(Jan) as Jan, SUM(Feb) as Feb, SUM(Mar) as Mar
from dbo.foobar
WHERE Participating_City = 'foofoo'

#3


2  

You can also use Coalesce and With Rollup.

您还可以使用Coalesce和Rollup。

SELECT COALESCE(Master_Code, 'TOTAL') AS MASTER_CODE, SUM(Jan), SUM(Feb), SUM(Mar)
FROM dbo.foobar
WHERE Participating_City = 'foofoo'
GROUP BY Master_Code WITH ROLLUP
ORDER BY Master_Code DESC