简体   繁体   中英

Nested SQL Statement not figuring SUM as expected

I am trying to do a quick accounting sql statement and I am running into some problems.

I have 3 tables registrations, events, and a payments table. Registrations are individual transactions, events are information about what they signed up for, and payments are payments made to events.

I would like to total the amounts paid by the registrations, put the event name and event startdate into a column, then total the amount of payments made so far. If possible I would also like to find a total not paid. I believe the bottom figures out everything except the payment amount total. The payment amount total is much larger than it should be, more than likely by using the SUM it is counting payments multiple times because of the nesting.

select 
  sum(`reg_amount`) as total, 
  event_name, 
  event_startdate, 
  (
    select sum(payment_amount) as paid 
    from registrations 
    group by events.event_id
  ) pay
FROM registrations 
  left join events 
    on events.event_id = registrations.event_id
  left join payments 
    on payments.event_id = events.event_id
group by registrations.event_id

First, you should use aliases so we know where all the fields come from. I'm guessing that payment_amount comes from the payments table and not from registrations .

If so, your subquery is adding up the payments from the outer table for every row in registrations. Probably not what you want.

I think you want something like this:

select sum(`reg_amount`) as total, 
       e.event_name, 
       e.event_startdate, 
       p.TotPayements
FROM registrations r left join
     events e
     on e.event_id = r.event_id left join
     (select event_id, sum(payment_amount) as TotPayments
      from payments
      group by event_id
     ) p
     on p.event_id = e.event_id
group by r.event_id;

The idea is to aggregate the payments at the lowest possible level, to avoid duplications caused by joining. That is, aggregate before joining.

This is a guess as to the right SQL, but it should put you on the right path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM