1

I am using the following SQL statement and I want it to to return null values if there are not any values hence "Coalesce", I have one problem though - it doesn't work :)

I think maybe because the row doesn't exist, so therefore how would I add that condition to the following statement?

SELECT 
  D1.dr, 
  D1.cr, 
  D1.asset_no, 
  (open_bal + dr - cr) AS closing_balance 
FROM (SELECT 
        COALESCE(SUM(dr_amount), 0) AS dr, 
        COALESCE(SUM(cr_amount), 0) AS cr, 
        asset_no 
      FROM posting, sysasset 
      WHERE posting.asset_no = @AssetNumber 
        AND period >= asset_open_per 
      GROUP BY asset_no) AS D1, asset 
WHERE D1.asset_no = asset.asset_no
4
  • uhmm if you want to return null, then why are you using COALESCE? can you explain more why it does not work? :D any error?
    – John Woo
    Jan 29, 2013 at 12:12
  • Just saying "it doesn't work" isn't very helpful. Can you add more details - what exactly is being returned and what do you expect?
    – ChrisF
    Jan 29, 2013 at 12:13
  • 1
    if the value doesn't exist, return null, but it cant return null if the row doesn't exists Jan 29, 2013 at 12:14
  • nothing is being returned Jan 29, 2013 at 12:14

2 Answers 2

1

oh i think the records are not displaying because some of them do not exist on the other table right? The reason why the aren't showing is because you are joining them using INNER JOIN, try this instead, use LEFT OUTER JOIN.

SELECT  D1.dr, 
        D1.cr, 
        D1.asset_no, 
        (COALESCE(open_bal,0) + dr - cr) AS closing_balance 
FROM 
    (
        SELECT  COALESCE(SUM(dr_amount), 0) AS dr, 
                COALESCE(SUM(cr_amount), 0) AS cr, 
                asset_no 
        FROM    posting
                LEFT JOIN sysasset 
                    ON  posting.asset_no = asset.asset_no
        WHERE   posting.asset_no = @AssetNumber  AND 
                period >= asset_open_per 
        GROUP   BY asset_no
    ) AS D1
    LEFT JOIN asset 
        ON D1.asset_no = asset.asset_no
1
  • Yes you are correct, i will try this and let you know, thanks Jan 29, 2013 at 12:19
1

Try replacing the coalesce with isnull. Expressions with coalesce can still be considered null. MSDN ref

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.