小编典典

如何获取结果集最后一行中所有列值的总和?

sql

我需要获取最后一行结果集的所有列值的总和。
这是我的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

像这样的东西:

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

阅读 260

收藏
2021-03-17

共1个答案

小编典典

假设没有空的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
2021-03-17