2010-01-21 79 views
1

值而不是字段名這是我的查詢如何獲得在逆透視查詢

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 

等等...... ............

獲取價值,而不是字段名在逆透視查詢

回答

1

這喲ur 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