如何将一列分成几列?

时间:2015-12-17 19:25:35

标签: mysql sql

我有一张桌子:

DataTable:
 id int,
 user_id int,
 field_id int,
 value varchar

DataExample:

id    user_id    field_id   value 
 1       1            1       'Peter'
 2       1            2       56
 3       1            3       100
 4       2            1       'Buzz'
 5       2            2       47
 6       2            3       120

我想将value列与field_id属性分开:

Name    Age     Score
Peter   56      100
Buzz    47      120

我试过了:

SELECT
    CASE
        WHEN field_id = 1 THEN  value
    END as Name,   
    CASE
        WHEN field_id = 2 THEN  value
    END as Age,
    CASE
        WHEN field_id = 3 THEN  value
    END as Score
    FROM Users u
    INNER JOIN DataTable t ON (t.user_id=u.id)

但得到了:

Name    Age     Score
Peter   null     null
null    56       null
null    null     100
Buzz    null      null
null    47       null
null    null      120

有任何建议吗?

1 个答案:

答案 0 :(得分:2)

您可以将GROUP BY应用于您的查询。您可以考虑Name分组id可能并不唯一:

SELECT id, MAX(Name) AS Name, MAX(Age) AS Age, MAX(Score) AS Score
FROM (
  SELECT u.id
  CASE
    WHEN field_id = 1 THEN  value
  END as Name,   
  CASE
    WHEN field_id = 2 THEN  value
  END as Age,
  CASE
    WHEN field_id = 3 THEN  value
  END as Score
  FROM Users u
  INNER JOIN DataTable t ON (t.user_id=u.id)
) AS sub
GROUP BY id;