2014-02-25 52 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' –

相关问题