SQL Server:如果引用表中的值相等,则从表中选择值

时间:2014-12-17 21:10:09

标签: sql sql-server sql-server-2008

我有两张桌子:单位

  name | departament | count  |  unit_manager   

unit_1 |   dep_1     |  100   |    nick         
unit_2 |   dep_1     |  200   |    john        

employees

full_name  |  unit  |  position  |  salary  |  phone_number  

    mary   | unit_2 |   clerk    |    100   |   123-45      
    nick   | unit_2 |  manager   |    200   |   24-56       

Employees表有一个外键unit,引用name表中的units列。

我需要编写一个SQL查询来选择所有单位,其中除单位经理以外的所有员工都有相同的职位。

我该怎么做?

我能找到的一切 - 就是如何从employees表中选择具有相似值的单位

SELECT u.*
FROM employee s1, employee s2
INNER JOIN units u ON s2.unit = u.name
WHERE s1.full_name <> s2.full_name 
AND s1.position = s2.position

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT u.*
FROM employee s1
INNER JOIN employee s2 ON s1.urID = s2.urID
INNER JOIN units u ON s2.unit = u.name
WHERE s1.full_name <> s2.full_name 
AND s1.position = s2.position

如果您没有返回想要的数据,请尝试:

SELECT u.*
FROM employee s1
INNER JOIN employee s2 ON s1.urID = s2.urID
LEFT OUTER JOIN units u ON s2.unit = u.name
WHERE s1.full_name <> s2.full_name 
AND s1.position = s2.position

要更好地处理如何正确连接,请参阅关于加入类型的Jeff Atwoods article

答案 1 :(得分:0)

我不得不对你想要的东西进行一些猜测,但试试这个...... 您的测试数据不足以测试结果,所以我添加了一些行... 这将返回unit_1,因为unit_1中的所有员工都是职员,而不是unit_2,因为unit_2中的1名员工不是职员&#39; (不包括经理)

create table #unit (name varchar(20),  departament varchar(20),  counta varchar(20),  unit_manager varchar(20))
insert into #unit values('unit_1','dep_1','100','nick');
insert into #unit values('unit_2','dep_1','200','john');

create table #employees(full_name varchar(20),  unit varchar(20),  position varchar(20))
insert into #employees values('nick','unit_1','manager');
insert into #employees values('mary1.1','unit_1','clerk');
insert into #employees values('mary1.2','unit_1','clerk');
insert into #employees values('mary1.3','unit_1','clerk');
insert into #employees values('mary1.4','unit_1','clerk');

insert into #employees values('john','unit_2','manager');
insert into #employees values('mary2.1','unit_2','clerk');
insert into #employees values('mary2.2','unit_2','not a clerk');
insert into #employees values('mary2.3','unit_2','clerk');
insert into #employees values('mary2.4','unit_2','clerk');


SELECT u.name AS Unit, COUNT(*) as Employees, COUNT(DISTINCT e1.Position) as Positions
FROM #unit u
    JOIN #employees e1 on u.name = e1.unit AND u.unit_manager <> e1.full_name
GROUP by u.name
HAVING COUNT(DISTINCT e1.Position) = 1

如果你想查看所有单位的清单,以及他们有多少不同的职位,请执行此操作

SELECT u.name AS Unit, COUNT(*) as Employees, COUNT(DISTINCT e1.Position) as Positions
FROM #unit u
    JOIN #employees e1 on u.name = e1.unit AND u.unit_manager <> e1.full_name
GROUP by u.name