2

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

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

回报:

在此处输入图像描述

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

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

我看了这个话题,但我的需求似乎不同。

4

1 回答 1

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;
于 2013-09-11T14:31:33.387 回答