2

我有两张桌子employees, salary_advance

employees表有列empid, name, salary并且salary_advanceid, empid, amount, date

我想显示所有员工的姓名,薪水,剩余..

remaining = ( salary - amount ) 

当我进行内部加入时,我只会得到提前的员工..

我想在员工中显示谁先行+其他员工..

这是我的 SQL 语句

select 
    employees.name , employees.salary , 
    (employees.salary - salary_advance.amount ) 
from 
    employees 
inner join 
    salary_advance on employees.empid = salary_advance.empid 
4

6 回答 6

4

您需要使用 aLEFT OUTER JOIN而不是您的INNER JOIN,并且您还需要使用ISNULL0 而不是NULLsalary_advance表中获取:

SELECT
    employees.name, 
    employees.salary, 
    Remaining = (employees.salary - ISNULL(salary_advance.amount, 0) ) 
FROM 
    employees 
LEFT OUTER JOIN 
    salary_advance ON employees.empid = salary_advance.empid 
于 2013-07-28T08:44:36.097 回答
2

使用左连接,并处理空值:

select
  e.name , e.salary,
  employees.salary - isnull(a.amount, 0)
from
  employees e
left outer join
  salary_advance a on e.empid = a.empid

isnull函数可能命名为ifnull,具体取决于您使用的数据库。

于 2013-07-28T08:54:40.463 回答
2

您也可以使用:

SELECT
    employees.name, 
    employees.salary, 
    ( CASE salary_advance.amount 
          WHEN NULL THEN employees.salary
          ELSE employees.salary - salary_advance.amount
      END  
    ) Remaining
FROM 
    employees 
LEFT OUTER JOIN 
    salary_advance ON employees.empid = salary_advance.empid 
于 2013-07-28T08:55:02.377 回答
2

如果员工可以有多个预付款,您将需要使用LEFT JOINwithSUMGROUP BY获得正确的结果。如果您只需要计算自某个日期以来的预付款,请将其添加到 ; 的ON子句中LEFT JOIN

SELECT employees.name , employees.salary ,
      (employees.salary - COALESCE(SUM(salary_advance.amount),0)) remaining 
FROM employees 
LEFT JOIN salary_advance 
  ON employees.empid = salary_advance.empid 
 AND salary_advance.date >= '2012-01-01'
GROUP BY employees.name, employees.salary

一个用于测试的 SQLfiddle

于 2013-07-28T08:48:48.750 回答
1

尝试这个:

select 
    employees.name , employees.salary , 
    Remaining = (employees.salary - ISNULL(salary_advance.amount, 0))
from 
    employees 
left join 
    salary_advance on employees.empid = salary_advance.empid

LEFT JOIN 关键字返回左表中的所有行,以及右表中的匹配行。

于 2013-07-28T08:43:08.633 回答
1

打印这个:

select
    employees.name, 
    employees.salary, 
    Remaining = (employees.salary - ISNULL(salary_advance.amount, 0) ) 
from
    employees 
left outer join
    salary_advance on employees.empid = salary_advance.empid 

而不是这个:

select 
    employees.name , employees.salary , 
    (employees.salary - salary_advance.amount ) 
from 
    employees 
inner join 
    salary_advance on employees.empid = salary_advance.empid  

摘要:您需要使用 aleft outer join而不是inner join

于 2013-07-28T08:44:47.740 回答