2012-03-21 58 views
1

我有一張存儲員工姓名和工作年限的表。這些列是:SQL查詢選擇*如果<this>但不是如果<condition>

employeeID int NOT NULL, 
year int NOT NULL 

主鍵是composite:employeeID和year。我需要選擇表格中2012年存在的那個employeeID的所有記錄,而不是2011年。換句話說,我需要一份2012年工作的員工名單,但不是2011年。我不知道爲什麼我不能這樣做!如果你理解了這個問題,請跳過下面的Java代碼。

如果我是來解析Java中員工的表這將是:

// This is what is returned at the end 
List theQueryResults = new List(); 

// This would be all employees and the years they worked, assume it's filled. 
Table employees = new Table (int employeeID, int year); 

for (int i = 0; i < employees.count(); i++) { 
    boolean addToQuery = false; 
    for (int j = 0; j < employees[0].length; j++) { 
     if (theArray[i][j] == 2011) { 
      addToQuery = false; 
      break; 
     } 
     if (theArray[i][j] == 2012) { addToQuery = true; } 
    } 

    if (addToQuery == true) { theQueryResults.add(employees[i].id); } 
} 

我會很感激的迴應。我有一個brainfart。

回答

4
SELECT employeeID 
FROM tab 
WHERE year = 2012 
and employeeID not in (SELECT employeeID FROM tab WHERE year = 2011) 
2

在Oracle中,你可以使用減號來

select employeeId from tab 
where year = 2012 
minus 
select employeeId from tab 
where year = 2011 
+0

這個won.t工作,因爲這兩個結果集之間的年份會有所不同。指定明確的列(例如,只是'employeeID')而不是'*'(任何其他列也可能使負運算符也不安) – 2012-03-21 05:04:45

+0

@Damien_The_Unbeliever謝謝!已在標準SQL中更新了我的回答 – 2012-03-21 05:14:59

+0

'minus' =='EXCEPT'。 – onedaywhen 2012-03-21 08:27:34

0
select employeeID, year 
from table 
where employeeID not in (select employeeID from table where year = 2011) 
and year = 2012 

對於MSSQL。

相關問題