在SQL WHERE子句中多次使用Same Column

时间:2018-05-29 19:39:21

标签: sql db2 where-clause

我正在寻找一种方法来编写一个返回结果的查询,其中列可以在WHERE语句中多次使用。无法找到最佳方法。

SELECT
  EMPLOYEE, CATEGORY, STATUS
FROM
  EMPLOYMENT
WHERE 
  (CATEGORY = 1 AND STATUS LIKE '%A%') AND (CATEGORY = 2 AND STATUS = 'B')

3 个答案:

答案 0 :(得分:1)

在这里看起来你想要'或':

function x = backsub(R,b)
% Backsub for upper triangular matrix.
[m,n] = size(R);
p = min(m,n);
x  = zeros(n,1);

    for i=p:-1:1
        % Look from bottom, assign to vector
        r = b(i);
        for j=(i+1):p
            % Subtract off the difference
            r = r-R(i,j)*x(j);
        end
        x(i) = r/R(i,i);
    end

end

function x2 = genresult(Q,R,b,x)
% Generates result

    b1 = Q'*b;
    x1 = backsub(R,b1);

    x2 = norm(x1-x)/norm(x);

end

答案 1 :(得分:1)

据推测,您希望员工具备这些条件。如果是这样,您可以使用聚合:

SELECT EMPLOYEE
FROM EMPLOYMENT
WHERE (CATEGORY = 1 AND STATUS LIKE '%A%') OR
      (CATEGORY = 2 AND STATUS = 'B')
GROUP BY EMPLOYEE
HAVING COUNT(DISTINCT CATEGORY) = 2;  -- matches both

答案 2 :(得分:0)

基本上您已经多次使用列名称(EX。CATEGORY = 1CATEGORY = 2)。

但问题还不够明确,为你提供这个问题的实际答案。

内部联接:

SELECT e1.EMPLOYEE, e1.STATUS
FROM EMPLOYMENT as e1
Inner join EMPLOYMENT as e2 on
  e2.EMPLOYEE = e1.EMPLOYEE and e2.STATUS = ‘B’ and e2.CATEGORY = 2
WHERE (e1.CATEGORY = 1 AND e1.STATUS LIKE '%A%')

这将显示CATEGORY = 1的员工的所有工作记录以及包含A的所有状态,同一员工在类别2中也有状态B

它应该返回与@Daniel

的查询相同的结果