不幸的是,MySQL 没有将行转换为列的 PIVOT 函数,因此您需要使用带有 CASE 表达式的聚合函数。
如果您的列数有限或已知,查询的基本语法将是:
select bank_name,
sum(case when month_year ='10/2011' then payment_sum else 0 end) `10/2011`,
sum(case when month_year ='11/2011' then payment_sum else 0 end) `11/2011`,
sum(case when month_year ='12/2011' then payment_sum else 0 end) `12/2011`
from
(
select bank_name,
payment_sum,
CONCAT(MONTH(payment_due_date), '/', YEAR(payment_due_date)) as month_year
from bank
join finance
on bank.bank_id = finance.bank_id
) d
group by bank_name;
但是对于您的情况,听起来您将有未知数量的日期,因此您可能需要使用准备好的语句来创建动态 sql:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when month_year = ''',
CONCAT(MONTH(payment_due_date), '/', YEAR(payment_due_date)),
''' then payment_sum end) AS `',
CONCAT(MONTH(payment_due_date), '/', YEAR(payment_due_date)), '`'
)
) INTO @sql
from finance;
SET @sql
= CONCAT('SELECT bank_name, ', @sql, '
from
(
select bank_name,
payment_sum,
CONCAT(MONTH(payment_due_date), ''/'', YEAR(payment_due_date)) as month_year
from bank
join finance
on bank.bank_id = finance.bank_id
) d
group by bank_name;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;