表A
DATANO, ITEM
-----------------------------
1001,1
1002,1
1002,2
1002,3
表B
DTATNO,ITEM
-------------------------
1002,3
我想要的结果是
DATANO, ITEM
-----------------------------
1001,1
1002,1
1002,2
不包含表B的数据
一个字段的我会,两个字段忽然不会了
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-07-16 15:54:13
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([DATANO] int,[ITEM] int)
insert [A]
select 1001,1 union all
select 1002,1 union all
select 1002,2 union all
select 1002,3
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([DTATNO] int,[ITEM] int)
insert [B]
select 1002,3
--------------开始查询--------------------------
select * from [A]
EXCEPT
select * from [B]
----------------结果----------------------------
/*
DATANO ITEM
----------- -----------
1001 1
1002 1
1002 2
*/
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-07-16 15:54:13
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([DATANO] int,[ITEM] int)
insert [A]
select 1001,1 union all
select 1002,1 union all
select 1002,2 union all
select 1002,3
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([DTATNO] int,[ITEM] int)
insert [B]
select 1002,3
--------------开始查询--------------------------
--2000以上
select * from [A]
EXCEPT
select * from [B]
--2000
SELECT *
FROM a a
WHERE NOT exists (SELECT 1 FROM b WHERE a.[DATANO]=b.[DTATNO] AND a.ITEM=b.ITEM)
----------------结果----------------------------
/*
DATANO ITEM
----------- -----------
1001 1
1002 1
1002 2
(3 行受影响)
DATANO ITEM
----------- -----------
1001 1
1002 1
1002 2
*/
------解决方案--------------------
select * from a
except
select * from b
------解决方案--------------------
select datano, item from A left join B on a.datano=b.datano and a.item=b.item
where b.datano is null