MYSQL表中的多个枢轴

时间:2015-08-06 02:24:02

标签: mysql

我的数据库有以下设置:

create table spooner_pec
(
  id int,
  year varchar(20),
  policy_number int,
  primary_name varchar(200),
  experience_rate decimal(10,2),
  mco_name varchar(200)
);

插入这些值:

insert into spooner_pec values
(1,'2009',183586,'ZBIN LANDSCAPING INC', 1.22, 'GENEX CARE FOR OHIO'),
(1,'2011',183586,'ZBIN LANDSCAPING INC', 0.93, 'COMPMANAGEMENT HEALTH SYSTEMS, INC.'),
(1,'2012',183586,'ZBIN LANDSCAPING INC', 0.92, 'HEALTH MANAGEMENT SOLUTIONS, INC.'),
(1,'2013',183586,'ZBIN LANDSCAPING INC', 0.50, 'CAREWORKS'),
(1,'2014',183586,'ZBIN LANDSCAPING INC', 0.47, 'UNIVERSITY HOSPITALS COMPCARE'),
(1,'2010',183586,'ZBIN LANDSCAPING INC', 1.27, 'SHEAKLEY UNICOMP')

我目前工作的查询是:

SET @sql = NULL;
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;
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;

因此,在此前的一个问题和一些研究之后,我终于得到了正确的工作。我基本上只是把所有的年份都用在列而不是行上。

所以我每个公司都有一行,然后是每年一年的笔列。现在我需要以同样的方式使用year-mco列,在我的声明中我是否添加了这个?

SQLFiddle

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

SET @sql = NULL;
SET @sql2 = NULL;
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;

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when year = ',
      year,
      ' then mco_name end) AS `',
      year, '-Mco`'
    ) ORDER BY year
  ) INTO @sql2
FROM
  spooner_pec;
SET @sql = CONCAT('SELECT policy_number, primary_name, ', @sql, ', ', @sql2, ' 
              FROM spooner_pec 
               GROUP BY policy_number');

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