我有两张表employees, salary_advance
。
employees
表格列empid, name, salary
,salary_advance
列id, 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
答案 0 :(得分:4)
您需要使用LEFT OUTER JOIN
代替INNER JOIN
,并且您还需要使用ISNULL
从NULL
获取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
SUM
和GROUP BY
来获得正确的结果。如果您只需要计算某个日期以来的预付款,请将其添加到ON
的{{1}}子句中;
LEFT JOIN
答案 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