Count Returning blank instead of 0

前端 未结 3 490
面向向阳花
面向向阳花 2020-12-06 09:52

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         


        
相关标签:
3条回答
  • 2020-12-06 10:41

    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)))
    
    0 讨论(0)
  • 2020-12-06 10:50

    Perhaps #AllExpired is empty, or one of the joins returns no results?

    Remember inner joins need results on both sides in order to return, so because #AllExpired is empty the join returns nothing.

    Change it to an OUTER join.

    0 讨论(0)
  • 2020-12-06 10:53

    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 have 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.

    0 讨论(0)
提交回复
热议问题