将多个Rows值组合到一个列中。

时间:2017-04-13 06:24:42

标签: mysql

  

这是表结构输出

first image

  

我想合并所有包和组件,输出如下:

second image

3 个答案:

答案 0 :(得分:0)

您可以使用CASE语句,只有在修复组件数量时才会解决问题

SELECT package, 
(CASE WHEN COMPONENT = 'WATER' THEN MARKS END) AS WATER,
(CASE WHEN COMPONENT = 'AIR' THEN MARKS END) AS AIR,
(CASE WHEN COMPONENT = 'FIRE' THEN MARKS END) AS FIRE
FROM TABLE_NAME;

答案 1 :(得分:0)

你只需PIVOT表。它给出了另一个演示文稿,但试试这个 -

SELECT
  t.Package,
  MAX(IF(t.Component = 'WATER', t.Marks, NULL)) AS Water,
  MAX(IF(t.Component = 'AIR', t.Marks, NULL)) AS Air,
  MAX(IF(t.Component = 'FIRE', t.Marks, NULL)) AS Fire
FROM
  table t
GROUP BY
  t.Package;

答案 2 :(得分:0)

假设组件出现的行取决于它在表中显示的顺序,您可以计算出连接的伪造密钥的行号,然后按

应用组。
/*
DROP TABLE IF EXISTS T;
CREATE TABLE T (ID INT AUTO_INCREMENT PRIMARY KEY,PACKAGE VARCHAR(10),COMPONENT VARCHAR(10), MARKS INT);

INSERT INTO T (PACKAGE,COMPONENT,MARKS) VALUES
('02ABC','WATER',20),('02ABC','WATER',15),('02ABC','AIR',16),('02ABC','AIR',18),('02ABC','AIR',6),
('02ABC','WATER',5),
('02MNO','WATER',10),('02MNO','AIR',5),('02MNO','FIRE',15);
*/

SELECT S.PACKAGE,
         #S.OCCURANCE,
         MAX(CASE WHEN S.COMPONENT = 'WATER' THEN S.MARKS ELSE 0 END) WATER,
         MAX(CASE WHEN S.COMPONENT = 'AIR' THEN S.MARKS ELSE 0 END) AIR,
         MAX(CASE WHEN S.COMPONENT = 'FIRE' THEN S.MARKS ELSE 0 END) FIRE
FROM
(
SELECT T.ID,T.PACKAGE,T.COMPONENT,T.MARKS,
         IF(CONCAT(T.PACKAGE,T.COMPONENT) <> @P ,@OCCURANCE:=1,@OCCURANCE:=@OCCURANCE+1) OCCURANCE,
         @P:=CONCAT(T.PACKAGE,T.COMPONENT) P
FROM (SELECT @OCCURANCE:=0,@P:='') O,T
ORDER BY T.PACKAGE,T.COMPONENT,T.ID
) S
GROUP BY S.PACKAGE,S.OCCURANCE