我有这样的数据:
ID (UID), EID (ID of record), Name (Name of meta-field), Value (value of meta-field)
- 1,1,Name,A
- 2,1,Note,B
- 3,1,Additional,C
- 4,2,Name,Z
- 5,2,Note,Z
- 6,2,Additional,Z
- 7,3,Name,RICE
- 8,3,Note,DICE
- 9,3,Additional,MICE
我需要一个看起来像这样的选择(视图):
EID, Name, Note, Additional
- 1,A,B,C
- 2,Z,Z,Z
- 3,Rice,Dice,Mice
我尝试了几个选择,但似乎无法得到它,或找到合适的答案有帮助,任何帮助都将非常感激。
答案 0 :(得分:0)
这对我有用(sqlFiddle)
SELECT t.EID, tname.Value Name, tnote.Value Note, tadd.Value Additional
FROM Table1 t
INNER JOIN Table1 tname ON tname.Name = "Name" AND tname.EID = t.EID
INNER JOIN Table1 tnote ON tnote.Name = "Note" AND tnote.EID = t.EID
INNER JOIN Table1 tadd ON tadd.Name = "Additional" AND tadd.EID = t.EID
GROUP BY t.EID
自从回答这个问题以来,我已经获得了除MySQL以外的SQL变种的更多知识。这将是一个(更优雅)的MS SQL-Server解决方案:
select * from (
select EID, Name as Col, Value from Table1
) p
pivot (
min(Value)
for Col in (Name, Note, Additional)
) pvt
(请注意,Name
到Col
的别名是必要的,因为它会与转化结果的Name
列冲突。