如何从必须连接到导致重复的另一个表的表中正确地求和总计

时间:2015-05-11 17:02:43

标签: sql oracle

我有两张如下表:

PAY_TABLE

EMPLID  PAY
123     100
123     150
123     150

DEDUCTION_TABLE

EMPLID  DEDUCTION
123     15
123     30

我希望得到如下结果:

TOTAL_PAY
400

我想用一个相当简单的查询得到那个结果,我觉得我错过了一个明显的方法,但我似乎无法弄明白是什么。

例如,此查询返回800,因为PAY_TABLE中的每一行在加入DEDUCTION_TABLE时都会重复:

SELECT SUM(PAY) AS TOTAL_PAY 
FROM PAY_TABLE JOIN DEDUCTION_TABLE USING(EMPLID);

此查询返回250,因为DISTINCT关键字会导致150中的第二个PAY_TABLE值被忽略:

SELECT SUM(DISTINCT PAY) AS TOTAL_PAY 
FROM PAY_TABLE JOIN DEDUCTION_TABLE USING(EMPLID);

可能有几种方法可以做到这一点,但我正在寻找最简单的方法来返回400的结果。

以下是创建示例表以使其更容易的一些代码:

WITH 
PAY_TABLE AS (
  SELECT 123 AS EMPLID, 100 AS PAY FROM DUAL
  UNION ALL 
  SELECT 123, 150 FROM DUAL
  UNION ALL 
  SELECT 123, 150 FROM DUAL
),
DEDUCTION_TABLE AS (
  SELECT 123 AS EMPLID, 15 AS DEDUCTION FROM DUAL 
  UNION ALL
  SELECT 123, 30  FROM DUAL
)

2 个答案:

答案 0 :(得分:2)

目前还不清楚你需要什么,因为你的例子没有使用DEDUCTION_TABLE表,但我相信你想要的是在你JOIN之前聚合:

;with pay AS (SELECT EmplID,SUM(PAY) AS Pay
              FROM PAY_TABLE
              GROUP BY EmplID
             )
     ,ded AS (SELECT EmplID,SUM(DEDUCTION) AS Ded
              FROM DEDUCTION_TABLE
              GROUP BY EmplID
              )
SELECT *
FROM pay
LEFT JOIN ded
  ON pay.EmplID = ded.EmplID

答案 1 :(得分:1)

假设您需要加入DEDUCTION_TABLE才能确保为员工扣除:

SELECT SUM(P.PAY) AS TOTAL_PAY 
FROM PAY_TABLE P
WHERE EXISTS (SELECT NULL FROM DEDUCTION_TABLE D
             WHERE D.EMPLID = P.EMPLID;