SQL 条件聚合

示例

付款表

顾客支付方式
彼得信用100
彼得信用300
约翰信用1000
约翰借方500

select customer, 
       sum(case when payment_type = 'credit' then amount else 0 end) as credit,
       sum(case when payment_type = 'debit' then amount else 0 end) as debit
from payments
group by customer

结果:

顾客信用借方
彼得4000
约翰1000500

select customer, 
       sum(case when payment_type = 'credit' then 1 else 0 end) as credit_transaction_count,
       sum(case when payment_type = 'debit' then 1 else 0 end) as debit_transaction_count
from payments
group by customer

结果:

顾客credit_transaction_countdebit_transaction_count
彼得20
约翰11