怎样两表联合筛选出如下数据,见正文:在线等
情境如下:
订单表A:
A01(订单号)
-----------
m01
m02
...
货品表B:
B01 B02
-----------
m01 'ok'
m01 'ok'
m01 'no'
m02 'ok'
m02 'ok'
...
想要得到如下结果:
原理是:只要A表中的订单号A01在B表中所对应的B02字段全部='ok',则把这些订单查询出来。
怎么用最简单的语句实现?
比如上面查询出来只有m01符合条件。
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-23 16:09:31
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([A01] varchar(3))
insert [A]
select 'm01' union all
select 'm02'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([B01] varchar(3),[B02] varchar(2))
insert [B]
select 'm01','ok' union all
select 'm01','ok' union all
select 'm01','no' union all
select 'm02','ok' union ALL
select 'm02','ok'
--------------开始查询--------------------------
select * from [A]
WHERE EXISTS (SELECT 1 FROM b WHERE a.[a01]=b.[b01] AND b.[b02]='ok')
AND NOT EXISTS (SELECT 1 FROM b WHERE a.[a01]=b.[b01] AND b.[b02]='no')
----------------结果----------------------------
/*
A01
----
m02
*/
select * from 订单表A
where A01 not in (select B01 from 货品表B where B02 = 'no')
if object_id('[A]') is not null drop table [A]
go
create table [A]([A01] varchar(3))
insert [A]
select 'm01' union all
select 'm02'
if object_id('[B]') is not null drop table [B]
go
create table [B]([B01] varchar(3),[B02] varchar(2))
insert [B]
select 'm01','ok' union all
select 'm01','ok' union all
select 'm01','no' union all
select 'm02','ok' union ALL
select 'm02','ok'
select A.A01
from A
inner join B
on a.A01 = b.B01
group by A.A01
having COUNT(case when b.B02 = 'Ok' then 1 else null end) = COUNT(*)
/*
A01
m02
*/