如何在Unpivot查询中获取值而不是fieldname

时间:2010-01-21 23:41:44

标签: sql sql-server

这是我的查询

Declare @SampleUNPivot Table(ID int ,Name varchar(50),a int,b int,c int,d int)

insert into @SampleUNPivot values(1,'name1',1,2,3,4)
insert into @SampleUNPivot values(2,'name2',10,20,30,40)
insert into @SampleUNPivot values(3,'name3',11,21,31,41)
insert into @SampleUNPivot values(4,'name4',14,24,34,44)

Select ID,Name,[SampleValue]
From (
Select ID,name,a,b,c,d from @SampleUNPivot) orig
UNPIVOT
( quantity for [SampleValue] in (a,b,c,d)) as UNPT

------------Current Result-------------
ID  Name    SampleValue
1   name1   a
1   name1   b
1   name1   c
1   name1   d
2   name2   a
2   name2   b
2   name2   c
2   name2   d
3   name3   a
3   name3   b
3   name3   c
3   name3   d
4   name4   a
4   name4   b
4   name4   c
4   name4   d

请更正上面的查询 结果如

ID  Name    SampleValue
1       name1          1
1       name1          2
1       name1          3
1       name1          4

依旧..................

在Unpivot查询中获取值而不是fieldname

1 个答案:

答案 0 :(得分:1)

那是你的quantity字段。

SELECT ID,Name,[SampleValue], quantity
FROM ( SELECT ID,name,a,b,c,d from @SampleUNPivot) orig
UNPIVOT ( quantity for [SampleValue] in (a,b,c,d)) as UNPT