MySQL组计数为2列?

时间:2016-12-15 22:24:06

标签: mysql sql

给定包含paymentspayer_id的{​​{1}}表

计算收到的付款将是:

recipient_id

您如何计算:用户所处的付款次数(用户可以是payer_id还是recipient_id)?

3 个答案:

答案 0 :(得分:1)

如果假设您想要计算 - 对于具有特定身份证的每个人 - 此人参与的支付交易数量,那么工会都应该提供帮助:

select person_id, count(*)
from ((select payer_id as person_id from payments) union all (select recipient_id as person_id from payments)) paymentsOfPerson
group by person_id
order by person_id DESC

如果付款还可以包含payer_id = recipient_id(从一个帐户转移到同一个人的另一个帐户)的记录,则必须注意这些转帐不会被计算两次:

select person_id, count(*)
from ((select payer_id as person_id from payments where payer_id != recepient_id) union all (select recipient_id as person_id from payments)) paymentsOfPerson
group by person_id
order by person_id DESC

答案 1 :(得分:0)

聚合前的一个方法是UNION ALL

select id, count(*) as cnt, sum(recipient) as recipient_cnt,
      sum(payer) as payer_cnt
from ((select recipient_id as id, 1 as recipient, 0 as payer
       from payments
      ) union all
      (select payer_id, 0, 1
       from payments
      )
     ) i
group by id;

答案 2 :(得分:0)

我认为这可以解决您的问题:

SELECT COUNT(*) as payments_count
    , COUNT(DISTINCT payer_id) distinct_payers
    , recipient_id
 FROM payments
GROUP BY recipient_id
ORDER BY payer_count DESC