【问题标题】:SQL Query select * if <this> but not if <condition>SQL 查询 select * if <this> 但不是 if <condition>
【发布时间】:2012-04-05 15:02:05
【问题描述】:

我有一个表格,其中存储了员工姓名和他们工作的年份。列是:

employeeID int NOT NULL,
year int NOT NULL

主键是复合的:employeeID 和 year。我需要选择该employeeID 存在2012 年而不是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); }
}

我将不胜感激。我脑子有问题。

【问题讨论】:

    标签: sql if-statement


    【解决方案1】:
    SELECT employeeID 
    FROM tab
    WHERE year = 2012
    and employeeID not in (SELECT employeeID FROM tab WHERE year = 2011)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这不会起作用,因为两个结果集的年份会有所不同。指定显式列(例如,仅 employeeID)而不是 *(任何其他列也可能会扰乱减号运算符)
      • minus == EXCEPT 在标准 SQL 中。
      【解决方案3】:
      select employeeID, year
      from table
      where employeeID not in (select employeeID from table where year = 2011)
      and year = 2012
      

      对于 MSSQL。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多