重新排列MYSQL枢轴中的行选择

时间:2015-06-26 01:09:26

标签: mysql sql pivot

我正在尝试使用一个轴来将一些行作为列。我对此声明的一切正常:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when year = ',
      year,
      ' then experience_rate end) AS `',
      year, '-Pen`'
    )
  ) INTO @sql
FROM
  spooner_pec order by year asc;
SET @sql = CONCAT('SELECT policy_number, primary_name, ', @sql, ' 
                  FROM spooner_pec 
                   GROUP BY policy_number');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

唯一的问题是,如果行中的年份出现故障,那么它们也会作为列出现故障。有没有办法用select?

重新排列列

SQLFiddle

1 个答案:

答案 0 :(得分:2)

您应该在order by year中添加group_concat

select
  group_concat(distinct
    concat(
      'max(case when year = ',
      year,
      ' then experience_rate end) AS `',
      year, '-Pen`'
    )
    order by year          
  ) into @sql
from
  spooner_pec;

SQLFiddle