SQL:在SQL Server中编写查询以显示薪水相同,部门相同但城市不同的员工记录

时间:2019-01-28 12:35:00

标签: sql sql-server left-join

有人可以解释如何找到查询结果,我正在创建wuery但我没有得到结果

数据库中有2个表

tbl部门

Deptno  Dname
10     ACCOUNTING
20     RESEARCH
30     SALES
40     OPERATIONS

tblEmployee

Empno   Empname Job        Dept  Salary City
7698    Blake   Manager     10   5000   new york
7782    Clark   Manager     10   8000   Berlin
7566    Jones   Manager     20   7000   london
7654    Martin  Salesman    30   20000  new york
7499    Allen   Salesman    30   20000  tokyo
7844    Turner  Salesman    30   17000  new york
7900    James   Clerk       20   1000   delhi
7521    Ward    Salesman    10   15000  new york

在此表中,我没有得到

的结果
  

第30条记录

我的SQL查询AS

select
    tblDepartment.Dname,
    tblEmployee.Empname,
    tblEmployee.Salary,
    tblEmployee.Empno
from
    tblDepartment
    left join tblEmployee
        on tblDepartment.Deptno = tblEmployee.Deptno 
where
    tblEmployee.Sal = tblEmployee.Sal

此查询返回相同的薪水,但我没有得到预期的结果, 任何有任何想法的机构都请帮助解决。谢谢

4 个答案:

答案 0 :(得分:2)

exists浮现在脑海:

select e.*
from tblEmployee e
where exists (select 1
              from tblEmployee e2
              where e2.Deptno = e.Deptno and
                    e2.Salary = e.Salary and
                    e2.city <> e.city
             );

答案 1 :(得分:1)

我想可能有2个以上的雇员在同一部门和不同的城市拥有相同的薪水,因此每个雇员需要1行:

select 
  d.Dname,
  t.Salary,
  t.Empno,
  t.Empname, 
  t.City 
from tblEmployee t 
inner join tblDepartment d
on d.Deptno = t.Dept
where exists (
  select 1 from tblEmployee 
  where 
    Empno <> t.Empno and
    City <> t.City and
    Dept = t.Dept and
    Salary = t.Salary
)
order by d.Dname, t.Salary, t.Empname 

答案 2 :(得分:1)

您可以对薪水和部门相同的用户进行计数,并将结果与​​按薪水,部门和城市进行的计数进行比较。此查询不使用自联接。

ggplot(na.omit(plotData), aes(R1, R2)) + 
      geom_tile(aes(fill = kappa))  +
      geom_text(aes(label = round(kappa, 2))) +
      facet_grid(Dimension ~ .)

答案 3 :(得分:0)

SELECT E1.EmpNo AS FirstEmp 
       ,E2.EmpNo AS SecondEmp
       ,E1.Salary
       ,E1.Dept 
FROM tblEmployee E1 inner join
     tblEmployee E2 ON E2.Salary = E1.Salary
                       AND E2.Dept = E1.Dept
                       AND E1.City <> E2.City