1

我有以下数据集:

 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 才能得到这个结果?

4

2 回答 2

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

或者你也可以使用这个动态查询(如果你不知道类型的数量)(对于 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;

看到这个 SQLFiddle

结果:

╔════╦═══════╦════╦════╦════╗
║ ID ║ PLACE ║ A  ║ B  ║ C  ║
╠════╬═══════╬════╬════╬════╣
║  1 ║ Home  ║ 12 ║ 15 ║ 16 ║
║  4 ║ Work  ║ 35 ║ 23 ║ 55 ║
╚════╩═══════╩════╩════╩════╝
于 2013-05-30T06:07:31.220 回答
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;
于 2013-05-30T06:07:57.193 回答