2016-01-26 74 views
1

假設我有一張僱員表,每個表只屬於一個部門。MS Sql:每次生成多個表格,但不包括某些行

我需要在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 

能否請你幫我產生這種結果。提前致謝。

我不需要很多表中的結果。就像上面那樣。

+0

一個查詢返回一個結果表,不會更多,永遠不會更少。 – jarlh

+0

結果中我不需要不同的表格。我將在每個排除中添加一個列,例如「不是」。我糾正了上述情況。感謝您的更正 – arvins

回答

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)

+0

非常感謝!你讓我今天一整天都感覺很好!!! – arvins

相關問題