--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([djbh] varchar(10),[spid] varchar(10),[shl] int)
insert [a]
select 'bh001' ,'sp001' ,10 union all
select 'bh001' ,'sp002' ,11 union all
select 'bh001' ,'sp003' ,15 union all
select 'bh002' ,'sp001' ,10 union all
select 'bh002' ,'sp002' ,11 union all
select 'bh002' ,'sp003' ,15 union all
select 'bh003' ,'sp001' ,97 union all
select 'bh003' ,'sp003' ,98 union all
select 'bh003' ,'sp004' ,99
select * from a
/*djbh spid shl
---------- ---------- -----------
bh001 sp001 10
bh001 sp002 11
bh001 sp003 15
bh002 sp001 10
bh002 sp002 11
bh002 sp003 15
bh003 sp001 97
bh003 sp003 98
bh003 sp004 99
(9 行受影响)
*/
--A:查询spid、shl及单据明细条数有相同的djbh
--处理测试数据
select *,row_number() over(PARTITION BY djbh order by djbh,spid) as rowid into #a from a
select * from #a
/*
djbh spid shl rowid
---------- ---------- ----------- --------------------
bh001 sp001 10 1
bh001 sp002 11 2
bh001 sp003 15 3
bh002 sp001 10 1
bh002 sp002 11 2
bh002 sp003 15 3
bh003 sp001 97 1
bh003 sp003 98 2
bh003 sp004 99 3
(9 行受影响)
*/
--按单据编号进行分组合并
SELECT [djbh],
(SELECT [spid]+',' FROM #a WHERE djbh=a.djbh
FOR XML PATH('')
) AS [spid] ,
(SELECT cast([shl] as varchar(10))+',' FROM #a WHERE djbh=a.djbh
FOR XML PATH('')
) AS [shl]
into #b
FROM #a a
GROUP BY [djbh]
select * from #b
/*
djbh spid shl
---------- ------------------------
bh001 sp001,sp002,sp003, 10,11,15,
bh002 sp001,sp002,sp003, 10,11,15,
bh003 sp001,sp003,sp004, 97,98,99,
(3 行受影响)
*/
--查询重复数量大于2的单据号
select djbh from
#b a,
(select spid,shl from #b group by spid,shl having count(djbh)>=2) b
where a.spid=b.spid and a.shl=b.shl
/*
djbh
----------
bh001
bh002
(2 行受影响)
*/
SQL Server 2005 行号、合并、分组
最新推荐文章于 2022-11-22 18:17:27 发布