在表中将行显示为列

时间:2012-12-29 07:10:34

标签: mysql sql select mysqli

我有一张像下面这样的表

CREATE TABLE Statistics(Stat_Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                        Period  VARCHAR(55),
                        Location VARCHAR(255),
                        Rate_per_SqFt INT)

表中的数据是

INSERT INTO Statistics(Period, Location, Rate_per_SqFt)
                VALUES('June', 'Location A', 2500),
                      ('June', 'Location B', 2740),
                      ('June', 'Location C', 3200),
                      ('July', 'Location A', 2650),
                      ('July', 'Location B', 2800),
                      ('July', 'Location C', 3250),
                      ('August', 'Location A', 2750),
                      ('August', 'Location B', 2950),
                      ('August', 'Location C', 3230),
                      ('October', 'Location A', 2950),
                      ('October', 'Location B', 3950),
                      ('October', 'Location C', 3530);

我希望输出中的特定月份的行显示为单独的列

 Period   Location A     Location B     Location C 
 June        2500          2740           3200
 July        2650          2800           3250
 August      2750          2950           3230
 October     2950          3950           3530  

如何使用查询

执行此操作

2 个答案:

答案 0 :(得分:4)

SELECT Period,
        MAX(CASE WHEN Location = 'Location A' THEN Rate_per_SqFt ELSE NULL END) `Location A`,
        MAX(CASE WHEN Location = 'Location B' THEN Rate_per_SqFt ELSE NULL END) `Location B`,
        MAX(CASE WHEN Location = 'Location C' THEN Rate_per_SqFt ELSE NULL END) `Location C`
FROM statistics
GROUP BY Period

如果您有未知位置数,则首选

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN Location = ''',
      Location,
      ''' then Rate_per_SqFt ELSE NULL end) AS ',
      CONCAT('`',Location,'`')
    )
  ) INTO @sql
FROM statistics;

SET @sql = CONCAT('SELECT Period, ', @sql, ' 
                   FROM Statistics 
                   GROUP BY Period');

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

答案 1 :(得分:1)

您可以在此处看到 5种方法将行转换为列(您提出的问题的摘要形式):methods link