4

我有一张如下表

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  

如何使用查询来做到这一点

4

1 回答 1

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

如果您有未知数量的位置,则首选动态 SQL

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;
于 2012-12-29T07:12:54.257 回答