SQL查询选择* if <this>但不选择<condition> </condition> </this>

时间:2012-03-21 04:51:29

标签: sql if-statement

我有一张表,用于存储员工姓名和工作年限。列是:

employeeID int NOT NULL,
year int NOT NULL

主键是composite:employeeID和year。我需要选择表中存在2012年员工ID的所有记录,但不是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); }
}

我很感激回应。我有一个脑力。

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

在Oracle中,您可以使用MINUS运算符

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

答案 2 :(得分:0)

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

对于MSSQL。