将Exist条件转换为使用T-SQL加入

时间:2016-07-18 13:27:17

标签: sql sql-server-2008 tsql

我正在尝试转换以下T-SQL Select查询以排除“存在”子句并包含“加入”子句。但我最终没有得到正确的结果。这个专家团队的一些人可以帮我提一些技巧。

select *
FROM HRData
INNER JOIN (
    SELECT eeceeid, MIN(eecdateoftermination) eTermDate
            FROM dbo.empcomp
            INNER JOIN 
            (
            SELECT xeeid FROM HRData_EEList
            INNER JOIN  dbo.empcomp t ON xeeid = eeceeid AND xcoid = eeccoid
            WHERE eecemplstatus = 'T' AND eectermreason <> 'TRO' AND eeccoid <> 'WAON6'
            AND EXISTS (    SELECT 1 FROM dbo.empded  
                            INNER JOIN dbo.dedcode on deddedcode = eeddedcode AND deddedtype = 'MED' AND (eedbenstopdate IS NULL OR eedbenstopdate > '12/31/2005')
                            WHERE eedeeid = xeeid AND eedcoid = xcoid )
            GROUP BY xeeid
            HAVING COUNT(*) > 1) Term ON xeeid = eeceeid
            group by eeceeid

) Terms ON eeid = eeceeid AND Termdate = eTermDate

2 个答案:

答案 0 :(得分:0)

有趣的请求。

select *
FROM HRData
INNER JOIN (
    SELECT eeceeid, MIN(eecdateoftermination) eTermDate
            FROM dbo.empcomp
            INNER JOIN 
            (
            SELECT xeeid FROM HRData_EEList
            INNER JOIN  dbo.empcomp t ON xeeid = eeceeid AND xcoid = eeccoid
            INNER JOIN 
            (    SELECT DISTINCT xeeid,  xcoid FROM dbo.empded  
                            INNER JOIN dbo.dedcode on deddedcode = eeddedcode AND deddedtype = 'MED' AND (eedbenstopdate IS NULL OR eedbenstopdate > '12/31/2005')
                           -- WHERE eedeeid = xeeid AND eedcoid = xcoid 
            ) AS A ON xeeid = A.xeeid AND eedcoid  = A.eedcoid
            WHERE eecemplstatus = 'T' AND eectermreason <> 'TRO' AND eeccoid <> 'WAON6'            
            GROUP BY xeeid
            HAVING COUNT(*) > 1) Term ON xeeid = eeceeid
            group by eeceeid

) Terms ON eeid = eeceeid AND Termdate = eTermDate

答案 1 :(得分:0)

EXISTS转换为JOIN的算法非常简单。

而不是

FROM   A
WHERE  EXISTS (SELECT *
               FROM   B
               WHERE  A.Foo = B.Foo) 

使用

FROM   A
       INNER JOIN (SELECT DISTINCT Foo
                   FROM   B) AS B
         ON A.Foo = B.Foo 

但第一个可能会更好地优化