J'ai besoin d'obtenir la somme de toutes les valeurs de colonne d'un résultat défini dans la dernière ligne.
Voici ma requête SQL.
Master_Code Jan Feb Mar
1 4 5 6
2 5 5 5
Total 9 10 11
3 Réponses :
Faites un syndicat où vous répétez la même requête, mais sans le groupement:
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'
en supposant qu'il n'y ait pas de lignes 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
+1 Vous pouvez utiliser le case lors du regroupement (master_code) = 1 puis «Total» d'autre Master_Code fin code> si la colonne est nullable.
Vous pouvez également utiliser des coalesce et avec le rouleau.
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