SQL查询返回表连接到自身之间的差异

时间:2013-07-03 03:28:08

标签: sql left-join sql-server-2012 self-join not-exists

我正在使用SQL Server 2012。

我有一个名为 AdvApp.vPortfolioGroupMemberFlattened 的视图 我想返回在portfoliogroupcode master 或portfoliogroupcode open 中的所有memberid,但不在两个组中。我不关心其他小组的成员。

以下stackoverflow文章接近我需要的内容,但在将表连接到自身时似乎不起作用。

sql query to return differences between two tables

这是我的桌子。

PortfolioGroupCode  MemberID    MemberCode
master              316         abc
master              317         def
open                316         abc
open                317         def
open                321         ghi
master              322         jkl
closed               89         lmn

这是我想要的结果,显示主人和开放成员之间的差异。

PortfolioGroupCode  MemberID    MemberCode
open                321         ghi
master              322         jkl

我在上述文章中尝试了以下两个查询。

SELECT A.*, B.*
FROM [AdvApp].[vPortfolioGroupMemberFlattened] a
FULL JOIN [AdvApp].[vPortfolioGroupMemberFlattened] b
ON (A.PortfolioGroupCode = B.PortfolioGroupCode)
WHERE A.PortfolioGroupCode IS NULL OR B.PortfolioGroupCode IS NULL

SELECT DISTINCT a.membercode, a.portfoliogroupcode
FROM [AdvApp].[vPortfolioGroupMemberFlattened] a
WHERE (
NOT EXISTS (
SELECT b.membercode
FROM [AdvApp].[vPortfolioGroupMemberFlattened] b
WHERE a.PortfolioGroupCode = 'master'
AND b.PortfolioGroupCode = 'open'
))

2 个答案:

答案 0 :(得分:1)

select distinct PortfolioGroupCode,  MemberID,    MemberCode 
from test 
where memberID not in (
     select distinct a.memberID from test a, test b
     where a.memberId = b.memberID 
     and a.PortfolioGroupCode in ('open','master')
     and a.PortfolioGroupCode <> b.PortfolioGroupCode) 
and PortfolioGroupCode in ('open','master')

以下是DEMO

答案 1 :(得分:0)

这项工作注意到与这些行的区别

 and a.PortfolioGroupCode = 'master'
 and b.PortfolioGroupCode = 'open'

工作查询

select distinct PortfolioGroupCode,  MemberID,    MemberCode 
from AdvApp.vPortfolioGroupMemberFlattened  
where memberID not in (
     select distinct a.memberID from AdvApp.vPortfolioGroupMemberFlattened  a, AdvApp.vPortfolioGroupMemberFlattened  b
     where a.memberId = b.memberID 
     and a.PortfolioGroupCode = 'master'
     and b.PortfolioGroupCode = 'open'
     and a.PortfolioGroupCode <> b.PortfolioGroupCode) 
and PortfolioGroupCode in ('open','master')