2014-02-25 101 views
2

我必須對單個行中的id,name和vale列中的每個id顯示id,類型和值(在三個不同的列中),如下所示。顯示同一行中的單個列的多個列

原始表

ID NAME VALUE 
1 Effort 10 
1 Type Development 
2 Type Testing 
2 Effort 20 
3 Type Testing 
3 Effort 20 

預計:

ID TYPE   VALUE 
1 Development 10 
2 Testing   20 
3 Testing   20 

而下面是我用來實現預期的結果查詢:

select id as id, 
case name when 'Type' then value else null end as TYPE, 
case name when 'Effort' then value else null end as value 
from tmn; 

但我得到一個稍微不同的結果形成我的預期之一爲:

ID TYPE   VALUE 
1    10 
1 Development 
2 Testing 
2    20 
3 Testing 
3    20 

配合,正如我前面提到的,請幫助實現這一點。

回答

1

試試這個,讓我知道你滿足

SELECT t1.ID, 
     t1.Name, 
     t2.Value 
FROM tmn As t1 
     Left Outer Join tmn As t2 
      On t1.ID = t2.ID 
      And t2.Name = 'Effort' 
WHERE t1.Name = 'Type' 
+0

謝謝玉。很酷的東西! –

1

下面是一個代碼示例,以獲得想要的結果:

declare @test table (id int, name varchar(25), value varchar(25)) 

insert into @test (id, name, value) 
select 1,'Effort','10' union all 
select 1,'Type','Development' union all 
select 2,'Type','Testing' union all 
select 2,'Effort','20' union all 
select 3,'Type','Testing' union all 
select 3,'Effort','20' 

select t1.id, t2.value, t1.value 
from (select id, value from @test where name='effort') t1 
join (select id, value from @test where name='type') t2 on t1.id=t2.id 

編輯:此代碼示例假設你有每個ID的努力/類型條目。如果不是,則可能需要更改爲完整外連接,但可能會返回空值。

替代的select語句應該是:

select t1.id, t2.value, t1.value 
from @test t1, @test t2 
where t1.name='effort' 
and t2.name='type' 
and t1.id=t2.id 
+0

謝謝JiggsJedi。它工作正常。 –

+0

也有可能獲得獨特的類型值和總和如下 'ID類型值 1發展10 2測試40' –

相關問題