日期:2014-05-17 浏览次数:20496 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 11:26:43
-- 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: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([Name] varchar(3),[Tlb] int,[div] int,[Result] varchar(4))
insert [huang]
select 'N-1',1,1,'Pass' union all
select 'N-1',1,2,null union all
select 'N-1',1,3,'f000' union all
select 'N-1',1,4,'f123' union all
select 'N-1',2,1,null union all
select 'N-1',2,2,null union all
select 'N-2',1,1,'Pass' union all
select 'N-2',1,2,'Pass' union all
select 'N-2',1,3,'Pass' union all
select 'N-2',1,4,'Pass'
--------------开始查询--------------------------
;WITH cte AS (
select DISTINCT name,tlb,'pass'result
from [huang] a
WHERE EXISTS (SELECT 1 FROM huang b WHERE a.NAME=b.NAME AND a.tlb=b.tlb AND b.result='pass')
AND NOT exists (SELECT 1 FROM huang b WHERE a.NAME=b.NAME AND a.tlb=b.tlb AND b.result<>'pass')
UNION ALL
select DISTINCT name,tlb,NULL result
from [huang] a
WHERE EXISTS (SELECT 1 FROM huang b WHERE a.NAME=b.NAME AND a.tlb=b.tlb AND b.result IS NULL )
AND NOT exists (SELECT 1 FROM huang b WHERE a.NAME=b.NAME AND a.tlb=b.tlb A