Monday, September 26, 2016

Use COALESECE in T-SQL to make columns which sum up nothing return a zero instead of NULL.

This...

SELECT c.CurrencyCode,
COUNT(i.TotalAmount) AS 'OpenInvoices',
SUM(i.TotalAmount) AS 'Balance',
COUNT(pdi.TotalAmount) AS 'PastDueInvoices',
SUM(pdi.TotalAmount) AS 'PastDueBalance'
FROM #Currencies c
LEFT JOIN #Invoices i ON c.CurrencyId = i.CurrencyId
LEFT JOIN #PastDueInvoices pdi ON c.CurrencyId = pdi.CurrencyId
GROUP BY CurrencyCode

 
 

...needs to become...

SELECT c.CurrencyCode,
COUNT(i.TotalAmount) AS 'OpenInvoices',
COALESCE(SUM(i.TotalAmount), 0) AS 'Balance',
COUNT(pdi.TotalAmount) AS 'PastDueInvoices',
COALESCE(SUM(pdi.TotalAmount), 0) AS 'PastDueBalance'
FROM #Currencies c
LEFT JOIN #Invoices i ON c.CurrencyId = i.CurrencyId
LEFT JOIN #PastDueInvoices pdi ON c.CurrencyId = pdi.CurrencyId
GROUP BY CurrencyCode

 
 

Get it?

No comments:

Post a Comment