2015-07-21 58 views
0

我必須編輯一個存儲過程,他必須返回具有可爲空值的三列的總和。如果有null值,我需要將其轉換爲0多列可加空值的總和

下面是數據的截圖:

enter image description here

,這裏是僅使用第一列originial要求:

SELECT SUM(reglProj.Montant) /* SUM of 'Montant', 'FraisMagasing', 'FraisVendeur' instead */ AS SommeReglement 
FROM Projet.LigneEcheancierProjet ligne 
INNER JOIN Projet.ReglementProjetEcheance reglProj ON reglProj.LigneEcheancierProjetId = ligne.LigneEcheancierProjetId 
.... 

您是否有一些在T-SQL中使用sumcase條件的最佳實踐?

+0

使用'isnull'或'coalesce'。 。 。 – sgeddes

+0

哪裏是你的其他2列在sql查詢中,你想投的 – Ajay2707

+1

你爲什麼要這麼做? ['SUM忽略空值](http://sqlfiddle.com/#!3/3171d/1)(基本上將它們視爲0)默認情況下... –

回答

2
--ANSI standard 
    SELECT SUM(COALESCE(col1,0)) + SUM(COALESCE(col2,0)) + SUM(COALESCE(col3,0)) 

--SQL Server Style  
    SELECT SUM(ISNULL(col1,0)) + SUM(ISNULL(col2,0)) + SUM(ISNULL(col3,0)) 

--The one wthout functions. It will work the same as previous OR FASTER.  
    SELECT SUM(CASE WHEN col1 IS NULL THEN 0 ELSE col1 END) + SUM(CASE WHEN col2 IS NULL THEN 0 ELSE col2 END) + SUM(CASE WHEN col3 IS NULL THEN 0 ELSE col3 END) 

爲自己選擇一個。

或者可能需要以下(如果你想按行補充資金):

--ANSI standard 
    SELECT SUM(COALESCE(col1,0) +COALESCE(col2,0) + COALESCE(col3,0)) 

--SQL Server Style  
    SELECT SUM(ISNULL(col1,0)+ ISNULL(col2,0) + ISNULL(col3,0)) 

--The one wthout functions. It will work the same as previous OR FASTER.  
    SELECT SUM(CASE WHEN col1 IS NULL THEN 0 ELSE col1 END + CASE WHEN col2 IS NULL THEN 0 ELSE col2 END + CASE WHEN col3 IS NULL THEN 0 ELSE col3 END) 
+0

Thx作爲結果。我編輯我的問題,因爲我需要做我的三列(在同一張表)的總和:'Montant','FraisMagasing','FraisVendeur' –

0

看來你正在尋找ISNULL實際上

SELECT SUM(ISNULL(reglProj.Montant,0) + ISNULL(FraisMagasing,0)+ ISNULL(FraisVendeur,0)) AS SommeReglement 
FROM Projet.LigneEcheancierProjet ligne 
INNER JOIN Projet.ReglementProjetEcheance reglProj ON reglProj.LigneEcheancierProjetId = ligne.LigneEcheancierProjetId 
1

在SQL Server中,(並可能在大多數(如果不是全部)關係數據庫)SUM默認情況下聚合功能ignores null values,所以真的不需要在其內部使用coalesceisnull

如果你希望所有的3列每一行的總和,那麼你需要使用ISNULL:

SELECT ISNULL(reglProj.Montant,0) + 
     ISNULL(reglProj.FraisMagasing ,0) + 
     ISNULL(reglProj.FraisVendeur,0) 
FROM Projet.LigneEcheancierProjet ligne 
INNER JOIN Projet.ReglementProjetEcheance reglProj 
     ON reglProj.LigneEcheancierProjetId = ligne.LigneEcheancierProjetId 

如果你需要的所有3列,你可以簡單地做這樣的聚集之和:

SELECT ISNULL(SUM(reglProj.Montant), 0) + 
     ISNULL(SUM(reglProj.FraisMagasing), 0) + 
     ISNULL(SUM(reglProj.FraisVendeur), 0) 
FROM Projet.LigneEcheancierProjet ligne 
INNER JOIN Projet.ReglementProjetEcheance reglProj 
     ON reglProj.LigneEcheancierProjetId = ligne.LigneEcheancierProjetId