SQL Server 2005 行號、合併、分組

--> 測試數據:[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 行受影響)
*/

發佈了50 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章