行转列-确定奇偶行SQL语句

 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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值