转换SQL表

时间:2010-12-14 08:58:26

标签: sql sql-server

我们有一个具有以下格式的表

RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40

我们想将此表示为:

John   30
Alice  40

任何人都有一个很好的解决方案吗?

4 个答案:

答案 0 :(得分:3)

SELECT
  TN.FieldValue AS ValueName
, TV.FieldValue AS ValueAge
FROM dbo.Table1 TN
INNER JOIN dbo.Table1 TV ON TN.RecordID = TV.RecordID
  AND TN.FieldName = 'Name'
  AND TV.FieldName = 'Age'

答案 1 :(得分:1)

为什么没有人使用枢轴?

declare @a TABLE(RecordId int, FieldName varchar(20), FieldValue varchar(20)) 

insert into @a select 1, 'Name', 'John' 
insert into @a select 1, 'Age', '30' 
insert into @a select 2, 'Name', 'Alice' 
insert into @a select 2, 'Age', '40' 

select *
from @a a pivot (max(FieldValue) for FieldName in (Name,Age)) p

答案 2 :(得分:0)

declare @a TABLE(RecordId int, FieldName varchar(20), FieldValue varchar(20))

insert into @a select 1, 'Name', 'John'
insert into @a select 1, 'Age', '30'
insert into @a select 2, 'Name', 'Alice'
insert into @a select 2, 'Age', '40'

select 
 records.RecordId 
 , name.fieldvalue [Name]
 , age.fieldvalue [Age]
from
 (select distinct recordid from @a) records
 inner join @a name on records.recordid = name.recordid and name.fieldname = 'Name'
 inner join @a age on records.recordid = age.recordid and age.fieldname = 'Age'

答案 3 :(得分:0)

这不是很好(但也不是数据),但如果在编写查询时知道列名称,这将有效:

SELECT 
RecordId, 
group_concat( if( FieldName = 'name', FieldValue, '' ) SEPARATOR '' ) AS person_name, 
group_concat( if( FieldName = 'age', FieldValue, '' ) SEPARATOR '' ) AS person_age
FROM test_table
GROUP BY RecordId

(适用于MySQL 5.0)

您还应该使用CAST将字段设置为正确的类型

如果你不知道这些字段,你需要(以编程方式)预先选择一个不同的FieldName来构建你的查询

我感觉Drupal内容创建工具包(CCK)做的事与此非常相似