将行更改为列

时间:2012-10-05 08:53:40

标签: sql sql-server-2008 tsql

我有这个问题:

SELECT     
   dbo.[Values].Value, dbo.Definition.FieldName, dbo.Definition.DefinitionID
FROM         
   dbo.Records AS R 
INNER JOIN
   dbo.[Values] ON R.RecordID = dbo.[Values].RecordID 
INNER JOIN
   dbo.Definition ON dbo.[Values].DefinitionID = dbo.Definition.DefinitionID

结果是:

Value   FieldName   DefinitionID
1   test new    6
4   abc 6
0   test new    7
0   abc 7
34  test new    8
910 abc 8

我试着这样做:

test new | abc | DefinitionID
1           4     6
0           0     7
34          910   8

我试图改变这一点,但没有成功。列dbo.[Values].Value的类型为nvarchar(MAX)

1 个答案:

答案 0 :(得分:0)

select [test new],[abc],DefinitionID
from
(
   -- your query here
SELECT     dbo.[Values].Value, dbo.Definition.FieldName, dbo.Definition.DefinitionID 
FROM         dbo.Records AS R INNER JOIN 
                      dbo.[Values] ON R.RecordID = dbo.[Values].RecordID INNER JOIN 
                      dbo.Definition ON dbo.[Values].DefinitionID = dbo.Definition.DefinitionID 
) src
PIVOT
(MAX(Value) for FieldName in ([test new],[abc])) p