我必须为具有id,name和vale的表中的每个id在单行中显示id,type和value(在三个不同的列中),如下所示。
原始表
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
Mates,正如我前面提到的,请帮助实现这一目标。
答案 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 t1.id, t2.value, t1.value
from @test t1, @test t2
where t1.name='effort'
and t2.name='type'
and t1.id=t2.id
答案 1 :(得分: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'