22,181
社区成员




select
a.管理编号,
max(isnull(cast((case rowno when 1 then a.所属编号 end)as nvarchar),'')) as NEW编号,
max(isnull(cast((case rowno when 2 then a.所属编号 end)as nvarchar),'')) as OLD编号
from tb a
group by 管理编号
/*
管理编号 NEW编号 OLD编号
----------- ------------------------------ ------------------------------
10000000001 2000 1777
10000000002 2875 2000
90000000001 2000
90000000002 2000
90000000003 2000
90000000004 2000
(6 行受影响)
*/
select
a.管理编号,
max(case rowno when 1 then a.所属编号 end) as NEW编号,
max(case rowno when 2 then a.所属编号 end) as OLD编号
from tb a
group by 管理编号
/*
管理编号 NEW编号 OLD编号
----------- ----------- -----------
10000000001 2000 1777
10000000002 2875 2000
90000000001 2000 NULL
90000000002 2000 NULL
90000000003 2000 NULL
90000000004 2000 NULL
警告: 聚合或其他 SET 操作消除了空值。
(6 行受影响)
*/
create table test(rowno int, 管理编号 varchar(20), 序号 int, 区分 int, 所属编号 int)
go
insert test select 2, '10000000001', 4, 2, 1777
insert test select 1, '10000000001', 5 ,2 ,2000
insert test select 2, '10000000002', 3, 2 ,2000
insert test select 1, '10000000002', 4, 2, 2875
insert test select 1, '90000000001', 1 ,9, 2000
insert test select 1, '90000000002', 1 ,9 ,2000
insert test select 1, '90000000003', 1, 9 ,2000
insert test select 1, '90000000004', 1, 9 ,2000
go
select a.管理编号,a.NEW编号,a.OLD编号 from (select 管理编号,区分,min(所属编号) OLD编号 ,max(所属编号) NEW编号 from test group by 管理编号,区分) a where a.OLD编号<>a.NEW编号
union all
select 管理编号,序号,区分 from test a where not exists(select 1 from test where 管理编号=a.管理编号 and 区分=a.区分 and (所属编号>a.所属编号 or 所属编号<a.所属编号))
go
/*
管理编号 NEW编号 OLD编号
-------------------- ----------- -----------
10000000001 2000 1777
10000000002 2875 2000
90000000001 1 9
90000000002 1 9
90000000003 1 9
90000000004 1 9
*/
drop table test
go
declare @t table(rowno int,管理编号 varchar(16),序号 int,区分 int,所属编号 int)
insert into @t select 2,'10000000001',4,2,1777
insert into @t select 1,'10000000001',5,2,2000
insert into @t select 2,'10000000002',3,2,2000
insert into @t select 1,'10000000002',4,2,2875
insert into @t select 1,'90000000001',1,9,2000
insert into @t select 1,'90000000002',1,9,2000
insert into @t select 1,'90000000003',1,9,2000
insert into @t select 1,'90000000004',1,9,2000
select
a.管理编号,
(case when b.rowno is null then a.序号 else a.所属编号 end) as NEW编号,
(case when b.rowno is null then a.区分 else b.所属编号 end) as OLD编号
from
(select * from @t where rowno=1) a
left join
(select * from @t where rowno=2) b
on
a.管理编号=b.管理编号
/*
管理编号 NEW编号 OLD编号
---------------- ----------- -----------
10000000001 2000 1777
10000000002 2875 2000
90000000001 1 9
90000000002 1 9
90000000003 1 9
90000000004 1 9
*/