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.
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.
As all of your values are null, count(cola) has to return zero.
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.
No, it will only return a zero (or non-zero) result.
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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With