0

我正在使用 SQL Server 2012。

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

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

sql 查询返回两个表之间的差异

这是我的桌子。

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

这是我想要的结果,显示了 master 和 open 成员之间的增量。

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'
))
4

2 回答 2

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')

这是演示

于 2013-07-03T03:49:17.617 回答
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')
于 2013-07-03T05:09:43.253 回答