if object_id('temptable') is not null
drop table temptable
create table temptable(图号 varchar(20),名称 varchar(20),原材料 varchar(20),数量 int)
insert into temptable values('TB3B121-0025','铰刀','YCL001',10)
insert into temptable values('TB3B121-0025','铰刀','YCL002',20)
insert into temptable values('TB3B121-0026','铣刀','YCL007',5)
insert into temptable values('TB3B121-0026','铣刀','YCL004',2)
insert into temptable values('TB3B121-0030','磨刀','YCL001',4)
insert into temptable values('TB3B121-0030','磨刀','YCL002',7)
select 图号,名称,
max(case px when 1 then 原材料 else null end) 头部材料,
max(case px when 1 then 数量 else null end) 头部数量,
max(case px when 2 then 原材料 else null end) 尾部材料,
max(case px when 2 then 数量 else null end) 尾部数量
from
(
SELECT *, (CASE WHEN 原材料 IN
(SELECT TOP 1 原材料
FROM temptable
WHERE 图号 = t .图号) THEN 1 ELSE 2 END) AS px
FROM temptable t
) table3
group by 图号,名称
drop table tb