MS Sql: 生成多个表,每次不包含某些行

MS Sql: Produce multiple tables excluding some rows each time

假设我有 table 名员工,每个员工只属于一个部门。

我需要在 ms sql 中编写一个查询,我将能够生成多个 table 并且在每个 table 中我想从一个部门中排除员工。

John   IT
Helen  HR
Doris  IT
Peter  SALES
Paul   SALES
Joane  HR

结果:

Helen  HR     not it
Peter  SALES  not it
Paul   SALES  not it
Joane  HR     not it

John   IT     not hr
Doris  IT     not hr
Peter  SALES  not hr
Paul   SALES  not hr

John   IT   not sales
Helen  HR   not sales
Doris  IT   not sales
Joane  HR   not sales

你能帮我生成这个结果吗?提前致谢。

我不需要很多 table 结果。就像上面的一样。

简单的回答,做一个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 服务器可能有别的东西?

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)