MySQL-如何将多行合并为多列和一行?

时间:2017-07-18 09:30:49

标签: mysql sql pivot

如果我有一个类似于这样的MySQL表:例如2014000是产品笔,有四种不同价格的abcd类型。和2014001是另一个产品电话,还有三种不同价格的efg。现在我想让一个产品的名称和价值一行。

id       code         name       value

1      2014000          A          10

2      2014000          B          9

3      2014000          C         11

4      2014000          D        12

5      2014001          E        100 

6      2014001          F        110

7     2014001           G        120

尊重结果:

         code              name1                  value1                 name2              value2               name3              value3             name4              value4  

         -----------       ---------              ---------          ---------              ---------   -----------       ---------              ---------          ---------              
         2014000          A                      10                   B                     9                C                      11                   D                 12
         2014001          E                     100                   F                     110             G                      120                  null              null    

CREATE TABLE T(ID INT,代码INT,NAME CHAR(1),VALUE VARCHAR(10));

插入T VALUES(1,2014000,'A','10'),(2,2014000,'B','9'),(3,2014000,'C','11'),( 4,2014000,'D','12'),(5,2014001,'E','100'),(6,2014001,'F','110'),(7,2014001,'G', '120');

-----后面只有两行,如果有四行以上,怎么办呢?

SELECT    T1.code,     T2.name AS name1,     T2.value AS value1,     T3.name AS name2,     T3.value AS value2 FROM(     SELECT code,MIN(ID) AS ID1,CASE COUNT(code) WHEN 1 THEN NULL ELSE MAX(ID) END AS ID2 FROM T GROUP BY code ) T1 LEFT JOIN T T2 ON T1.ID1 = T2.ID LEFT JOIN T T3 ON T1.ID2 = T3.ID

1 个答案:

答案 0 :(得分:0)

SELECT t.code
     , t1.name name1
     , t1.value value1
     , t2.name name2
     , t2.value value2
     , t3.name name3
     , t3.value value3
     , t4.name name4
     , t4.value value4
  FROM ( SELECT code
              , group_concat(ID) ids
           FROM T
           GROUP BY code
       ) t
    LEFT JOIN T t1
      ON find_in_set(t1.ID,t.ids)=1
    LEFT JOIN T t2
      ON find_in_set(t2.ID,t.ids)=2
    LEFT JOIN T t3
      ON find_in_set(t3.ID,t.ids)=3
    LEFT JOIN T t4
      ON find_in_set(t4.ID,t.ids)=4