使用CREATE VIEW将列值拆分为多个列

时间:2013-05-06 11:20:27

标签: mysql sql create-view

使用MySQL查询,我如何获取如示例A中的表:

Example A
+------+---------------+----------+
| id   | value         | class    |
+------+---------------+----------+
| 1    | 33.00         | total    |
| 1    | 12.00         | shipping |
| 2    | 45.00         | total    |
| 2    | 15.00         | shipping |
+------+---------------+----------+

并创建一个类似于例B的视图?

Example B
+------+---------------+---------------+
| id   | value_total   | value_shipping|
+------+---------------+---------------+
| 1    | 33.00         | 12.00         |
| 2    | 45.00         | 15.00         |
+------+---------------+---------------+

2 个答案:

答案 0 :(得分:0)

试试这个

  select id , 
  max(case when class = 'total' then value end) as value_total
 , max(case when class = 'shipping' then value end) as value_shipping
  from Table1
  group by id

DEMO HERE

答案 1 :(得分:0)

您只需使用SUM()功能:

SELECT id
,SUM(CASE WHEN class = 'total' THEN value ELSE 0 END) AS value_total
,SUM(CASE WHEN class = 'shipping' THEN value ELSE 0 END) AS value_shipping
FROM Table1 
GROUP BY id;

请参阅this SQLFiddle

如果您的 class 数量未知,请尝试此动态查询

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when class = ''',
      class,
      ''' then value else 0 end) AS `value_',
      class, '`'
    )
  ) INTO @sql
FROM Table1;


SET @sql = CONCAT('SELECT id, ', @sql, '
                  FROM Table1 
                  GROUP BY id');

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

输出:

╔════╦═════════════╦════════════════╗
║ ID ║ VALUE_TOTAL ║ VALUE_SHIPPING ║
╠════╬═════════════╬════════════════╣
║  1 ║          33 ║             12 ║
║  2 ║          45 ║             15 ║
╚════╩═════════════╩════════════════╝

请参阅this SQLFiddle