0

I'm struggling with the below code. i'm trying to work out the total balance of a folio by using its total charges and total payments. i'm almost there, however with the below code the payments is incorrect, it seems to be multiplying the total sum of payments by the number of entries in charges. i'm guessing this is because I've connected the payments and charges, which I needed to do to filter out the checkin date which is only on pms sales.

can anyone help?

thanks

SELECT DISTINCT 'PMS AD' AS APP,
    FOLIO_ID,
       SUM(TOTAL_CHARGES) as TOTAL_CHARGES,
       SUM(TOTAL_PAYMENTS) as TOTAL_PAYMENTS
FROM ((SELECT DISTINCT P1.FOLIO_ID AS FOLIO_ID, SUM(P1.CHARGE_CODE_AMOUNT) AS TOTAL_CHARGES, 0 AS TOTAL_PAYMENTS
       FROM DEV.VR_PMS_SALES P1
       WHERE P1.CHARGE_CODE_AMOUNT <> 0 AND
             P1.ITEM_OPERATING_DAY IS NOT NULL
        AND P1.ITEM_OPERATING_DAY <= '03-DEC-2014'
        AND P1.CHECKIN_DATE <= '03-DEC-2014'
       GROUP BY P1.FOLIO_ID
      ) UNION ALL
      (SELECT DISTINCT P2.FOLIO_ID AS FOLIO_ID, 0 AS TOTAL_CHARGES, SUM(P2.AMOUNT) AS TOTAL_PAYMENTS
       FROM DEV.VR_PMS_PAYMENTS P2,
    DEV.VR_PMS_SALES P3
       WHERE P2.FOLIO_ID = P3.FOLIO_ID
    AND P2.AMOUNT <> 0
    AND P2.PMS_OPERATING_DAY <= '03-DEC-2014'
    AND P3.CHECKIN_DATE <= '03-DEC-2014'
       GROUP BY P2.FOLIO_ID
      )
     ) F
GROUP BY FOLIO_ID

EDIT:

Sorry I didn't provide examples. table data below

VR_PMS_PAYMENTS

VR_PMS_SALES

The issue I am having is that when running the sql it is multiplying the sum of p1.amount by the number of entries in VR_PMS_SALES. eg folio 4 is returning as 165 instead of 55. I need it to return the below...

desired outcome

I hope this is clearer.

thank you

BWILLIAMS
  • 1
  • 1
  • 1
    Looks like you need LEFT JOIN instead of UNION ALL and should not mention DEV.VR_PMS_SALES in the second query at all. – Serg Dec 07 '19 at 08:46
  • It would be helpful if you shared an example of your data – JoPapou13 Dec 07 '19 at 11:18
  • Sample data and desired results would make it possible for other people to understand your query. Basically, your question says "this complicated query doesn't do what I want. Make it work." And it doesn't show what "work" means. – Gordon Linoff Dec 07 '19 at 13:38
  • Apologies, I have added more info to the question – BWILLIAMS Dec 07 '19 at 15:17

0 Answers0