从两个表中选择的SQL语句

时间:2013-07-28 08:39:56

标签: sql database

我有两张表employees, salary_advance

employees表格列empid, name, salarysalary_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 

6 个答案:

答案 0 :(得分:4)

您需要使用LEFT OUTER JOIN代替INNER JOIN,并且您还需要使用ISNULLNULL获取0而不是salary_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 表:

{{1}}

答案 1 :(得分:2)

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

LEFT JOIN

An SQLfiddle to test with

答案 2 :(得分: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,具体取决于您使用的数据库。

答案 3 :(得分: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 

答案 4 :(得分: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关键字返回左表中的所有行,右表中包含匹配的行。

答案 5 :(得分: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  

摘要:您需要使用left outer join代替inner join