当前位置: 代码迷 >> Sql Server >> 怎么排除对应重复数据的单号
  详细解决方案

怎么排除对应重复数据的单号

热度:22   发布时间:2016-04-24 10:36:09.0
如何排除对应重复数据的单号
-------A表--------
单号
A01
A02
A03
A04

-------B表--------
单号  箱号
A01  CARTONA011
A01  CARTONA012
A01  CARTONA013

A02  CARTONA021
A02  CARTONA022
A02  CARTONA023
A03  CARTONA011
A03  CARTONA031
A03  CARTONA032
A03  CARTONA033

A04  CARTONA041

可以看出,B表中A01和A03出现重复使用同一个箱号的情况

查询A表单号时,如果B表中的箱号对应两个单号,那么,这种单号不可被查询到

考虑到,随着时间推移,B表数据会越来越多,为不影响查询效率,不可以使用count,或者说在查询时不可以每次都要对整个B表进行扫描

请大神指导有没有更优的sql


------解决方案--------------------
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2014-06-05 22:20:20
-- Version:
--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 
-- Feb 10 2012 19:13:17 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([单号] varchar(3))
insert [A]
select 'A01' union all
select 'A02' union all
select 'A03' union all
select 'A04'
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go 
create table [b]([单号] varchar(3),[箱号] varchar(10))
insert [b]
select 'A01','CARTONA011' union all
select 'A01','CARTONA012' union all
select 'A01','CARTONA013' union all
select 'A02','CARTONA021' union all
select 'A02','CARTONA022' union all
select 'A02','CARTONA023' union all
select 'A03','CARTONA011' union all
select 'A03','CARTONA031' union all
select 'A03','CARTONA032' union all
select 'A03','CARTONA033' union all
select 'A04','CARTONA041'
--------------开始查询--------------------------
select * from a where not exists(select 单号 from b t where exists(select 1 from b where 单号<>t.单号 and 箱号=t.箱号) and 单号=a.单号)
----------------结果----------------------------
/* 单号
----
A02
A04

(2 行受影响)
*/
  相关解决方案