Rea*_*oka 10 sql sql-server sql-server-2005
我需要获取最后一行中结果集的所有列值的总和.
这是我的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
Run Code Online (Sandbox Code Playgroud)
这样的事情:
Master_Code Jan Feb Mar
1 4 5 6
2 5 5 5
Total 9 10 11
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 16
建立一个联合,您重复相同的查询,但没有分组:
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'
Run Code Online (Sandbox Code Playgroud)
小智 11
假设没有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
Run Code Online (Sandbox Code Playgroud)
您还可以使用 Coalesce 和 With 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
71619 次 |
最近记录: |