简体   繁体   English

嵌套的SQL语句未按预期计算SUM

[英]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. 我正在尝试执行快速记帐sql语句,但遇到了一些问题。

I have 3 tables registrations, events, and a payments table. 我有3个表格注册,事件和一个付款表格。 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. 付款总金额比其应有的要大得多,由于使用嵌套,因此使用SUM多次计数付款的可能性更大。

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 . 我猜到payment_amount来自payments表而不是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. 这是对正确的SQL的猜测,但是它应该使您走上正确的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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