MS Sql:每次产生多个表,不包括某些行

时间:2016-01-26 10:41:07

标签: sql sql-server sql-server-2014

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

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

即。

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

你能帮助我产生这个结果吗?提前谢谢。

结果中我不需要很多表。就像上面那样。

1 个答案:

答案 0 :(得分:1)

简单回答,做一个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)