首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

急救啊如何在查询的时候,判断一个表a中3条(或多条)id相同的明细数据在表a中是否有相同的3条数据

2013-12-28 
急救啊,怎么在查询的时候,判断一个表a中3条(或多条)id相同的明细数据在表a中是否有相同的3条数据求救啊,怎

急救啊,怎么在查询的时候,判断一个表a中3条(或多条)id相同的明细数据在表a中是否有相同的3条数据
求救啊,怎么在查询的时候,判断一个表a中3条(或多条)单据id相同的明细数据(商品id不同)在表a中是否有相同的3条数据
[解决办法]


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 行受影响)

--处理测试数据
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 行受影响)

热点排行