22,181
社区成员




---测试数据---
if object_id('[a]') is not null drop table [a]
go
create table [a]([货号] varchar(3),[颜色] varchar(4),[箱号] int,[重量] int)
insert [a]
select '001','红色',1,20 union all
select '001','红色',2,40 union all
select '001','红色',3,10 union all
select '001','红色',4,23 union all
select '001','红色',5,32 union all
select '001','红色',6,45 union all
select '001','黑色',4,23 union all
select '001','黑色',5,32 union all
select '001','白色',6,45 union all
select '001','绿色',7,43
---查询---
select a1.货号,a1.颜色,a1.箱号 as 箱号1,a1.重量,a2.箱号 as 箱号2,a2.重量,a3.箱号 as 箱号3,a3.重量,a4.箱号 as 箱号4,a4.重量
from
(select * from(select *,px=(select count(1)+1 from a where 颜色=ta.颜色 and 箱号<ta.箱号) from a ta) tb where px%4=1) a1
left join
(select * from(select *,px=(select count(1)+1 from a where 颜色=ta.颜色 and 箱号<ta.箱号) from a ta) tb where px%4=2) a2
on a1.货号=a2.货号 and a1.颜色=a2.颜色 and a2.px=a1.px+1
left join
(select * from(select *,px=(select count(1)+1 from a where 颜色=ta.颜色 and 箱号<ta.箱号) from a ta) tb where px%4=3) a3
on a1.货号=a3.货号 and a1.颜色=a3.颜色 and a3.px=a1.px+2
left join
(select * from(select *,px=(select count(1)+1 from a where 颜色=ta.颜色 and 箱号<ta.箱号) from a ta) tb where px%4=0) a4
on a1.货号=a4.货号 and a1.颜色=a4.颜色 and a4.px=a1.px+3
---结果---
货号 颜色 箱号1 重量 箱号2 重量 箱号3 重量 箱号4 重量
---- ---- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
001 红色 1 20 2 40 3 10 4 23
001 红色 5 32 6 45 NULL NULL NULL NULL
001 黑色 4 23 5 32 NULL NULL NULL NULL
001 白色 6 45 NULL NULL NULL NULL NULL NULL
001 绿色 7 43 NULL NULL NULL NULL NULL NULL
(所影响的行数为 5 行)
create table tb(货号 varchar(10), 颜色 varchar(10), 箱号 int, 重量 int)
insert into tb values('001' , '红色' , 1 , 20 )
insert into tb values('001' , '红色' , 2 , 40 )
insert into tb values('001' , '红色' , 3 , 10 )
insert into tb values('001' , '红色' , 4 , 23 )
insert into tb values('001' , '红色' , 5 , 32 )
insert into tb values('001' , '红色' , 6 , 45 )
insert into tb values('001' , '黑色' , 4 , 23 )
insert into tb values('001' , '黑色' , 5 , 32 )
insert into tb values('001' , '白色' , 6 , 45 )
insert into tb values('001' , '绿色' , 7 , 43 )
go
select 货号 , 颜色,
max(case (px - 1)%4 when 0 then 箱号 end) 箱号1,
max(case (px - 1)%4 when 0 then 重量 end) 重量1,
max(case (px - 1)%4 when 1 then 箱号 end) 箱号2,
max(case (px - 1)%4 when 1 then 重量 end) 重量2,
max(case (px - 1)%4 when 2 then 箱号 end) 箱号3,
max(case (px - 1)%4 when 2 then 重量 end) 重量3,
max(case (px - 1)%4 when 3 then 箱号 end) 箱号4,
max(case (px - 1)%4 when 3 then 重量 end) 重量4
from
(
select * , px = (select count(1) from tb where 货号 = t.货号 and 颜色 = t.颜色 and 箱号 < t.箱号) + 1 from tb t
) m
group by 货号 , 颜色 , (px - 1)/4
order by 货号 , 颜色
drop table tb
/*
货号 颜色 箱号1 重量1 箱号2 重量2 箱号3 重量3 箱号4 重量4
---------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
001 白色 6 45 NULL NULL NULL NULL NULL NULL
001 黑色 4 23 5 32 NULL NULL NULL NULL
001 红色 1 20 2 40 3 10 4 23
001 红色 5 32 6 45 NULL NULL NULL NULL
001 绿色 7 43 NULL NULL NULL NULL NULL NULL
(所影响的行数为 5 行)
*/