单个SQL表上的聚合计算查询

时间:2014-03-18 13:01:36

标签: mysql sql

在我的数据库中,我有一个表payers_payments,包含一些外键(payer_idpayment_id)和一些数据透视字段(amount,{{1} })。

pays

每行代表| id | payer_id | payment_id | amount | pays | |----|----------|------------|--------|------| | 1 | 1 | 1 | 20 | 0 | | 2 | 2 | 1 | 23 | 1 | | 4 | 1 | 2 | 14 | 1 | | 5 | 2 | 2 | 17 | 1 | | 6 | 1 | 3 | 10 | 1 | | 7 | 2 | 3 | 0 | 0 | payer的贡献。 payment字段指定是否应在付款中包含pays

payer的总费用是给定payment的{​​{1}}的总和。因此,如果我想看看我将支付多少付款费用:

amount

同样,给定payment_id(例如,付款人1)贡献的总金额为:

SELECT SUM(amount) AS sumOfPayment 
  FROM payers_payments  
 WHERE payment_id=2;

现在,我想要做的是使用公平分享的概念。公平份额是付款的总费用除以payer为该付款SELECT SUM(amount) AS sumOfPayment FROM payers_payments WHERE payer_id=1; 的人数。我能表达的最简单的方法是使用子查询:

payers

对于给定的pay=1SELECT SUM(payers_payments.amount) / (SELECT count(*) FROM payers_payments WHERE pays AND payers_payments.payment_id = 3 ) AS FairShare FROM payers_payments WHERE payment_id=3 GROUP BY payers_payments.payment_id; ,他们的公平份额定义为:

payer

我的问题是,我希望查询根据每笔付款的公平份额以及是否包含在付款中,为每个payment获取总公平份额。 (如果SELECT IF(pays, FairShare, 0) as payerFairShare FROM payers_payments WHERE payer_id = 1 AND payment_id=3; --FairShare is the query as above 那么他们的公平份额是0)

根据以上数据,这是我为2位付款人提供的结果:

payer

有没有办法在单个查询中实现这一点,还是我必须对结果集进行一些循环? 我对RDMS不可知,但像MySQL这样的东西很好。

1 个答案:

答案 0 :(得分:2)

我首先编写的查询可以支付单个付款的份额。也就是说,按payment_id,所有金额的总和除以需要支付的人数。然后可以将该结果连接回原始数据。

SELECT
  payers_payments.payer_id,
  SUM(payers_payments.amount                      )   AS total_paid,
  SUM(payers_payments.pays * payments.single_share)   AS fair_share
FROM
  payers_payments
INNER JOIN
(
  SELECT
    payment_id,
    SUM(amount) / SUM(pays)   AS single_share
  FROM
    payers_payments
  GROUP BY
    payment_id
)
  AS payments
    ON  payers_payments.payment_id = payments.payment_id
GROUP BY
   payers_payments.payer_id

(payment_id)(payer_id)上都有索引是有益的。

在DECIMAL数据类型中使用amount字段将是有益的,尽管您需要考虑要对舍入做什么。 (总共支付10.00需要分三种方式,每种方式3.33,然后你想要在备用0.01上发生什么?)