SQL将行插入为列

时间:2013-10-23 00:44:05

标签: sql select view pivot-table entity-attribute-value

我有这样的数据:

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

我尝试了几个选择,但似乎无法得到它,或找到合适的答案有帮助,任何帮助都将非常感激。

1 个答案:

答案 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

(请注意,NameCol的别名是必要的,因为它会与转化结果的Name列冲突。