如何获取要显示为列的信息?

时间:2013-05-30 06:05:08

标签: mysql sql

我有以下数据集:

 ID | Place | Type | Count
 1  | Home  | A    | 12
 2  | Home  | B    | 15
 3  | Home  | C    | 16
 4  | Work  | A    | 35
 5  | Work  | B    | 23
 6  | Work  | C    | 55

我想最终:

 ID | Place | A  | B  | C
 1  | Home  | 12 | 15 | 16
 3  | Work  | 35 | 23 | 55

获取此结果需要什么样的SQL?

2 个答案:

答案 0 :(得分:0)

尝试此静态查询(如果您已知且数量有限的类型):

SELECT MIN(ID) AS ID, Place
  ,SUM(CASE WHEN Type = 'A' THEN Count ELSE 0 END) AS A
  ,SUM(CASE WHEN Type = 'B' THEN Count ELSE 0 END) AS B
  ,SUM(CASE WHEN Type = 'C' THEN Count ELSE 0 END) AS C
FROM MyTable
GROUP BY Place

或者您也可以使用此动态查询(如果您不知道Type的数量)(对于MySQL):

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when `Type` = ''',
      `Type`,
      ''' then Count END) AS `',
      `Type`, '`'
    )
  ) INTO @sql
FROM MyTable;

SET @sql = CONCAT('SELECT MIN(ID) AS ID, Place, ', @sql, '
                  FROM MyTable 
                   GROUP BY Place 
                  ');

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

请参阅this SQLFiddle

结果:

╔════╦═══════╦════╦════╦════╗
║ ID ║ PLACE ║ A  ║ B  ║ C  ║
╠════╬═══════╬════╬════╬════╣
║  1 ║ Home  ║ 12 ║ 15 ║ 16 ║
║  4 ║ Work  ║ 35 ║ 23 ║ 55 ║
╚════╩═══════╩════╩════╩════╝

答案 1 :(得分:0)

由于您没有提到任何RDBMS,因此该查询将适用于许多RDBMS。

SELECT  MIN(ID) ID,
        Place,
        MAX(CASE WHEN Type = 'A' THEN count END) A,
        MAX(CASE WHEN Type = 'B' THEN count END) B,
        MAX(CASE WHEN Type = 'C' THEN count END) C
FROM    TableName
GROUP   BY Place

如果您的Type数量未知,那么这是动态版本。

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN Type = ''',
               Type,
               ''' THEN Count ELSE NULL END) AS ',
               CONCAT('`', Type, '`')
               )) INTO @sql
FROM TableName;

SET @sql = CONCAT('SELECT MIN(ID) ID,s.Place, ', @sql, ' 
                   FROM TableName s
                   GROUP BY s.Place');

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

从两个声明输出

+----+-------+----+----+----+
| ID | PLACE | A  | B  | C  |
+----+-------+----+----+----+
|  1 | Home  | 12 | 15 | 16 |
|  4 | Work  | 35 | 23 | 55 |
+----+-------+----+----+----+

更新1

注意:GROUP_CONCAT结果长度仅限于group_concat_max_len系统变量的值,其默认值为1024.因此,如果您有大量列,则此值可以在使用GROUP_CONCAT函数之前设置得更高,例如:

SET @@group_concat_max_len = 5000;