MySql有多个总和检查一列

时间:2014-03-09 11:59:36

标签: mysql case-when

表:发票

id   amount     status  
1    100        PAID    
1    200        PAID    
1    500        UNPAID
1    100        UNPAID 

我希望在状态的基础上求和 结果:

id      paid_amt    unpaid_amt
1       300         600

请您提供解决方案吗?

1 个答案:

答案 0 :(得分:0)

在求和之前,您需要旋转案例以获得所需的结果。

试试这个:

select 
  id,
  sum( paid_amount ) as paid_amount,
  sum( unpaid_amount ) as unpaid_amount
from(
  SELECT
    id,
    case status when 'PAID' then amount else 0 end paid_amount,
    case status when 'UNPAID' then amount else 0 end unpaid_amount
  FROM Invoice
) pay_report
group by id