2013-02-02 54 views
0

我的第一篇文章,希望得到一些幫助。我需要創建一份報告,顯示從未退休的員工。我需要從3個表中提取信息。如果員工具有特定的扣稅代碼(7001至7006),則已經退休。我有以下表格和專欄。需要查詢來找到沒有退休的員工

Employee 
Employee.empid 
Employee.fname 
Employee.lname 
Employee.jobclass 


EarnHistory 
EarnHistory.empid 
EarnHistory.hoursworked 
EarnHistory.checknumber 
EarnHistory.checkdate 


DeductionHistory 
DeductionHistory.empid 
DeductionHistory.deductioncode 
DeductionHistory.checknumber 
DeductionHistory.checkdate 

查詢需要EMPID拉,FNAME,LNAME,hoursworked,deductioncode 凡僱員從來沒有經歷過7006

繳存扣減代碼7001,我曾嘗試使用NOT EXISTS

+0

的SQL Server?任何[小提琴](http://sqlfiddle.com)? –

+2

你應該包括你的查詢沒有工作,這樣,有人可以嘗試解釋爲什麼它沒有工作和更好的方式來做到這一點。 – R0MANARMY

+0

SQL Server 2008.您的權利,我應該發佈原始查詢。當我回到辦公室時,我會發布查詢。 – user2034546

回答

0

像這樣的東西應該工作:

SELECT E.empid, E.fname, E.lname, EH.hoursworked, DH.deductioncode 
FROM Employee E 
    INNER JOIN EarnHistory EH ON E.empid = EH.empid 
    INNER JOIN DeductionHistory DH ON E.empid = DH.empid 
    LEFT JOIN DeductionHistory DH2 ON E.empid = DH2.empid 
     AND DH2.deductioncode IN (7001,7002,7003,7004,7005,7006) 
WHERE DHD2.empid IS NULL 

這取決於您deductioncode數據類型。您可以使用BETWEEN,<>,或者添加撇號if varchar。

您還可以使用NOT EXISTS

SELECT E.empid, E.fname, E.lname, EH.hoursworked, DH.deductioncode 
FROM Employee E 
    INNER JOIN EarnHistory EH ON E.empid = EH.empid 
    INNER JOIN DeductionHistory DH ON E.empid = DH.empid 
WHERE NOT EXISTS (SELECT * 
        FROM DeductionHistory 
        WHERE deductioncode IN (7001,7002,7003,7004,7005,7006) 
        AND E.empid = DeductionHistory.empid) 

好運。

+0

我會給NOT EXISTS子句一個嘗試。我忘了一個細節。我還需要將結果限制在有特定付款方式的員工身上。在EarnHistory表中有一列叫做paytype,我需要限制結果爲支付類型100到150. – user2034546

+0

只需在WHERE條件中添加WHERE EH.PayType BETWEEN 100 AND 150 AND(假定它是一個數字數據類型)。 ..或者你可以鏈接它在你的JOIN。祝你好運。 – sgeddes

0
select Employee.empid, Employee.fname , Employee.lname,EarnHistory.hoursworked,   DeductionHistory.deductioncode from Employee 
    join EarnHistory using('empid') 
    join DeductionHistory using('empid') 
    LEFT JOIN DeductionHistory dh ON Empployee.empid = dh.empid 
    AND DH.deductioncode IN (7001,.......,7006) 
    WHERE DHD.empid IS NULL 
0
SELECT E.empid, E.fname, E.lname, EH.hoursworked, DH.deductioncode 
    FROM Employee E, EarnHistory EN, DeductionHistory DH 
WHERE E.empid = EH.empid 
    AND E.empid = DH.empid 
    AND E.empid <> (SELECT empid 
        FROM DedutionHistory 
        GROUP BY empid 
        HAVING deductioncode >= 7001 
         AND deductioncode <= 7006) 
相關問題