Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How return a count(*) of 0 instead of NULL

I have this bit of code:

SELECT Project, Financial_Year, COUNT(*) AS HighRiskCount
INTO #HighRisk 
FROM #TempRisk1
WHERE Risk_1 = 3
GROUP BY Project, Financial_Year

where it's not returning any rows when the count is zero. How do I make these rows appear with the HighRiskCount set as 0?

like image 344
alamodey Avatar asked Nov 07 '11 04:11

alamodey


2 Answers

Wrap your SELECT Query in an ISNULL:

SELECT ISNULL((SELECT Project, Financial_Year, COUNT(*) AS hrc
INTO #HighRisk 
FROM #TempRisk1
WHERE Risk_1 = 3
GROUP BY Project, Financial_Year),0) AS HighRiskCount

If your SELECT returns a number, it will pass through. If it returns NULL, the 0 will pass through.

like image 40
Steve Mol Avatar answered Sep 23 '22 02:09

Steve Mol


Use:

   SELECT x.Project, x.financial_Year, 
          COUNT(y.*) AS HighRiskCount
     INTO #HighRisk 
     FROM (SELECT DISTINCT t.project, t.financial_year
             FROM #TempRisk1
            WHERE t.Risk_1 = 3) x
LEFT JOIN #TempRisk1 y ON y.project = x.project
                      AND y.financial_year = x.financial_year
 GROUP BY x.Project, x.Financial_Year

The only way to get zero counts is to use an OUTER join against a list of the distinct values you want to see zero counts for.

like image 61
OMG Ponies Avatar answered Sep 23 '22 02:09

OMG Ponies