答案很簡單,做一個UNION ALL
:
select emp, dep, 'not it' from tablename where dep <> 'IT'
UNION ALL
select emp, dep, 'not hr' from tablename where dep <> 'HR'
UNION ALL
select emp, dep, 'not sales' from tablename where dep <> 'SALES'
更普遍的答案,做了SELF JOIN
:
select t1.emp, t1.dep, 'not ' || t2.dep
from tablename t1
join (select distinct dep from tablename) t2 ON t1.dep <> t2.dep
order by t2.dep
哪裏||
是ANSI SQL級聯。也許MS SQL Server可能有其他的東西?
SQL>create table tablename (emp varchar(10), dep varchar(10));
SQL>insert into tablename values ('John','IT');
SQL>insert into tablename values ('Helen','HR');
SQL>insert into tablename values ('Doris','IT');
SQL>insert into tablename values ('Peter','SALES');
SQL>insert into tablename values ('Paul','SALES');
SQL>insert into tablename values ('Joane','HR');
SQL>select t1.emp, t1.dep, 'not ' || t2.dep
SQL& from tablename t1
SQL& join (select distinct dep from tablename) t2 ON t1.dep <> t2.dep
SQL& order by t2.dep
SQL&;
emp dep
========== ========== ==============
John IT not HR
Doris IT not HR
Peter SALES not HR
Paul SALES not HR
Helen HR not IT
Peter SALES not IT
Paul SALES not IT
Joane HR not IT
John IT not SALES
Helen HR not SALES
Doris IT not SALES
Joane HR not SALES
12 rows found
如果您想要小寫的部門名稱,您可以做LOWER(t2.dep)
。
一個查詢返回一個結果表,不會更多,永遠不會更少。 – jarlh
結果中我不需要不同的表格。我將在每個排除中添加一個列,例如「不是」。我糾正了上述情況。感謝您的更正 – arvins