Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Returning blank instead of 0

Tags:

Good day everyone. Here is my code:

SELECT 
    'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.fld_LOAN)) as [Month]
    ,COUNT(PIT.fld_ID)'COUNT'
    ,SUM (PIT.fld_GRAM)'GRAMS'
    ,SUM (PH.fld_AMNT)'PRINCIPAL'
FROM  #AllExpired AE
    INNER JOIN Transactions.tbl_ITEM PIT
    ON AE.fld_MAINID=PIT.fld_MAINID
    INNER JOIN Transactions.tbl_HISTO PH
    ON AE.fld_MAINID =PH.fld_MAINID
GROUP BY DATENAME(MM,(DATEADD(MM,4,AE.fld_LOAN)))

The problem I'm facing is that my Count function does not return 0 if it has no values, Sum function does not return NULL if there are no resulting values retrieved. Instead, it just outputs blank. Why is that so and how can I fix it?

Here is a screenshot of sample output.

A

Of course this is not what I want. I want it to output zero and null. Please help me, I do not know what's wrong. Thank you.

like image 373
Albert Laure Avatar asked Oct 07 '13 09:10

Albert Laure


People also ask

Does Count return 0 or NULL?

As all of your values are null, count(cola) has to return zero.

Does count Return 0 SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Will count (*) ever return NULL?

No, it will only return a zero (or non-zero) result.


2 Answers

You cannot expect any records to be outputted when using a GROUP BY clause, when no records exist in your source.

If you want an output of 0 from the SUM and COUNT functions, then you should not use GROUP BY.

The reason is that when you have no records, the GROUP BY clause has nothing to group by, and then is not able to give you any output.

For example:

SELECT COUNT(*) FROM (SELECT 'Dummy' AS [Dummy] WHERE 1 = 0) DummyTable

will return one record with the value '0', where as:

SELECT COUNT(*) FROM (SELECT 'Dummy' AS [Dummy] WHERE 1 = 0) DummyTable
GROUP BY [Dummy]

will return no records.

like image 149
Dan Avatar answered Sep 28 '22 07:09

Dan


I would imagine you need to change your joins from INNER to OUTER to ensure rows are returned even when there is no corresponding record in tbl_PawnItem -

SELECT 
    'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.fld_LoanDate)) as [Month]
    ,COUNT(PIT.fld_PawnItemID)'COUNT'
    ,SUM (PIT.fld_KaratGram)'GRAMS'
    ,SUM (PH.fld_PrincipalAmt)'PRINCIPAL'
FROM  #AllExpired AE
    LEFT JOIN Transactions.tbl_PawnItem PIT
        ON AE.fld_PawnMainID=PIT.fld_PawnMainID
    LEFT JOIN Transactions.tbl_PawnHisto PH
        ON AE.fld_PawnMainID=PH.fld_PawnMainID
GROUP BY DATENAME(MM,(DATEADD(MM,4,AE.fld_LoanDate)))
like image 41
GarethD Avatar answered Sep 28 '22 07:09

GarethD