ID不同时的SUM(SALARY)

时间:2013-12-10 16:22:49

标签: sql oracle distinct decode sqlplus

我在尝试解决这个问题时遇到了麻烦,我只想补充一点工资 员工的身份是不同的。我以为我可以使用decode()函数执行此操作,但我无法定义适合的表达式。我的目标是

SUM(DECODE(S.ID,IS DISTINCT,S.SALARY))

但这不起作用!

所以完整查询看起来像

SELECT B.ID, SUM(S.SALARY), COUNT(DISTINCT S.ID), COUNT(DISTINCT RM.MEMBER_ID)
FROM BRANCH B 
INNER JOIN STAFF S ON S.BRANCH_ID = B.ID
INNER JOIN RECRUIT_MEMBER RM ON RM.BRANCH_ID = B.ID
GROUP BY B.ID;

但是问题在于SUM(S.SALARY)它会从重复的ID中增加工资

4 个答案:

答案 0 :(得分:0)

我不知道DECODE,但这应该有效:

SELECT 
  SUM(S.SALARY)
FROM <table> S
WHERE NOT EXISTS (
  SELECT ID FROM <table> WHERE ID=S.ID GROUP BY ID HAVING COUNT(*)>1
)

答案 1 :(得分:0)

也许是这样的......

SELECT E.ID, SUM(E.Salary)
FROM Employers E
WHERE E.ID IN (SELECT DISTINCT E2.ID FROM Employers E2)
GROUP BY E.ID

如果没有,也许您可​​以发布一些样本数据,以便我能更好地理解

答案 2 :(得分:0)

连接引入了重复的行。解决此问题的一种方法是添加行号以顺序识别不同的ID。真正的方法是修复连接,这样就不会发生,但这是第一种方式:

SELECT B.ID, SUM(CASE WHEN SEQNUM = 1 THEN S.SALARY END),
       COUNT(DISTINCT S.ID), COUNT(DISTINCT RM.MEMBER_ID)
FROM (SELECT B.ID, S.ID, RM.MEMBER_ID,
             ROW_NUMBER() OVER (PARTITION BY S.ID ORDER BY S.ID) as seqnum
      FROM BRANCH B 
      INNER JOIN STAFF S ON S.BRANCH_ID = B.ID
      INNER JOIN RECRUIT_MEMBER RM ON RM.BRANCH_ID = B.ID
     ) t
GROUP BY B.ID

答案 3 :(得分:0)

你可以像这样创建一个每个ID只有一个薪水的虚拟表......

SELECT
   ...whatever fields you've already got...
   s.Salary
FROM
   ...whatever tables and joins you've already got...

   LEFT JOIN (SELECT ID, MAX(SALARY) as "Salary" FROM SALARY_TABLE GROUP BY ID) s
   ON whatevertable.ID = s.ID