Split column values into multiple columns with CREATE VIEW

半世苍凉 提交于 2019-12-23 03:50:10

问题


With a MySQL query, how can I take a table like in Example A:

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

And create a view like Example B?

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

回答1:


You can simply use SUM() function for that:

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;

See this SQLFiddle

If you have unknown number of class then try this Dynamic query

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;

Output:

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

See this SQLFiddle




回答2:


try this

  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



来源:https://stackoverflow.com/questions/16397666/split-column-values-into-multiple-columns-with-create-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!