2013-07-03 60 views
0

我使用SQL Server 2012的SQL查詢表之間的回差,與其自身連接

我有一個名爲視圖AdvApp.vPortfolioGroupMemberFlattened 我想回到所有MEMBERID的是在portfoliogroupcode 或portfoliogroupcode open但不在兩個組中。我不關心其他組的成員。

下面的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 

這是我期望的結果,顯示了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' 
)) 

回答

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

+0

查詢分析器是顯示我一個錯誤,其中溫度;是。我得到這個錯誤有或沒有分號。我也可以刪除溫度;並且查詢運行但這不是正確的結果。謝謝 –

+0

解決了這個錯誤。重新檢查它 – chetan

+0

我可以讓你的測試工作,但由於某種原因,在實際數據庫中返回的結果是空白的? –

0

該作品注意到這些線路

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

工作QUER的disctinction ÿ

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