2

我有以下 SQL 代码:

select distinct members_main.membership_type,
payment_method,sum(amount_paid) 
from members_main, members_payments
where members_main.contact_id=members_payments.contact_id 
group by members_main.membership_type,payment_method 

这将返回以下内容:

在此处输入图像描述

我希望能够以下表网格格式返回结果:

在此处输入图像描述

有谁知道我是否或如何在 MySQL 中做到这一点?

谢谢,

约翰

4

2 回答 2

0

MySQL 没有数据透视函数,但您可以使用CASE表达式和聚合函数将行转换为列:

select  m.membership_type,
    sum(case when p.payment_method = 'Cash' then amount_paid else 0 end) Cash,
    sum(case when p.payment_method = 'Credit Card' then amount_paid else 0 end) CreditCard,
    sum(case when p.payment_method = 'Paypal' then amount_paid else 0 end) Paypal
from members_main m
inner join members_payments p
    on m.contact_id=p.contact_id 
group by m.membership_type;

如果您将拥有未知数量的payment_method',那么您将需要考虑使用准备好的语句来生成动态 SQL:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN p.payment_method = ',
      payment_method,
      ' THEN amount_paid else 0 END) AS `',
      payment_method, '`'
    )
  ) INTO @sql
FROM members_payments ;

SET @sql 
  = CONCAT('SELECT m.membership_type, ', @sql, ' 
            from members_main m
            inner join members_payments p
                on m.contact_id=p.contact_id 
            group by m.membership_type');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-05-08T14:00:50.400 回答
0

根据数据的复杂性,或者采用 bluefeet 的方式,或者如果 payment_method 金额是动态的,那么听起来您需要一个数据透视表。试试看这个

于 2013-05-08T14:04:28.327 回答