使用IN和子查询从多个表中选择数据

时间:2015-11-19 13:26:32

标签: sql-server

我在SQL Server中有三个表:

  1. 收费
  2. 津贴
  3. 扣减
  4. 所有这些列都有以下列:empID,Amount。

    我正在编写一个查询,使用IN从所有三个表中选择金额。以下是我的查询

    Select sum(P.Amount), sum(A.Amount), sum(D.Amount)
    from Pay P, Allowances A, Deductions D
    where P.empID=A.empID=D.empID IN (Select EmpId from Employees)
    

    基本上我希望逐个获得每位员工的薪资,津贴和扣除。但我无法正确查询。

1 个答案:

答案 0 :(得分:0)

看起来你需要一个UNION ALL查询:

SELECT empID, 'Pay' AS fromtable, Amount
FROM Pay
WHERE empID IN (1200,1201)
UNION ALL
SELECT empID, 'Allowances' AS fromtable, Amount
FROM Allowances
WHERE empID IN (1200,1201)
UNION ALL
SELECT empID,  'Deductions' AS fromtable, Amount
FROM Deductions
WHERE empID IN (1200,1201)