Split column values into multiple columns with CREATE VIEW

谁说我不能喝 提交于 2019-12-06 16:04:55

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

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

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