将行值转置为列

时间:2013-09-08 13:45:59

标签: mysql pivot

我的查询很简单 - 它每月/每年抓取银行及其交易金额:

select bank_name, 
   sum(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
group by bank_name, month_year

返回:

enter image description here

如何将行值(month_year)转换为列,然后pay_sum也转发到相应的month_year生成列?

我正在寻找一种方法来按月找到每家银行的付款总额。

我查看了this主题,但我的需求似乎有所不同。

1 个答案:

答案 0 :(得分:2)

不幸的是,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;