将表行转置为列

时间:2010-11-30 04:19:19

标签: mysql transpose

我有一张看起来像这样的表:

id  response_id     name        value
6   13          gender         female
5   13          workingArea    Sch
3   12          workingArea    IT
4   12          gender         male

我想转换成这样的东西:

response_id          workingArea   gender
12                IT           male
13                Sch          female

我可以知道怎么做吗?

1 个答案:

答案 0 :(得分:3)

假设您的第一张桌子是SOURCETABLE而您的第二张桌子是TARGETTABLE

INSERT INTO TARGETTABLE(response_id, workingArea, gender)
SELECT a.response_id response_id, 
       a.value workingArea, 
       b.value gender
  FROM SOURCETABLE a, SOURCETABLE b
 WHERE a.response_id = b.response_id
   AND a.name <> b.name
   AND a.name = 'workingArea'
   AND b.name = 'gender'