SQL - 使用Sum命令将同一人的工资相乘

时间:2016-09-25 08:29:05

标签: sql sql-server

我正在努力提高那些至少治疗2名患者10%的员工的工资。我的问题是,对于他们治疗的每位患者,薪水首先乘以2,然后在结束时乘以10%。例如,如果员工获得25.000并且对待3个人,则新工资变为82.500。

select distinct t.empNbr, e.Salary, sum(e.Salary*1.1) as NewSalary from Treats t
inner join Employee e
on e.empNbr=t.empNbr
WHERE t.empNbr IN
(
SELECT empNbr
  FROM Treats
  GROUP BY empNbr
  HAVING COUNT(*) >= 2)
group by t.empNbr, e.Salary

3 个答案:

答案 0 :(得分:1)

CROSS APPLY应该有所帮助:

SELECT  e.empNbr,
        e.Salary, 
        e.Salary*1.1 as NewSalary
FROM Employee e
CROSS APPLY (
    SELECT  empNbr
    FROM Treats
    WHERE e.empNbr = empNbr
    GROUP BY empNbr
    HAVING COUNT(*) > 1
    ) as t

t部分得到我们需要的empNbr。然后我们从empNbr表中选择salaryEmployee并做数学运算:)

还有一种方法:

SELECT  TOP 1 WITH TIES 
                        e.empNbr,
                        e.Salary, 
                        e.Salary*1.1 as NewSalary
FROM Employee e
INNER JOIN Treats t
    ON e.empNbr = t.empNbr
ORDER BY 
    CASE WHEN COUNT(t.empNbr) OVER (PARTITION BY t.empNbr ORDER BY t.empNbr) > 1 THEN 1 ELSE 0 END DESC,
        ROW_NUMBER() OVER (PARTITION BY t.empNbr ORDER BY t.empNbr)

答案 1 :(得分:0)

这应该是正确的查询。如果有效,请告诉我

select empNbr, Salary, sum(Salary*1.1) as NewSalary 
from employee 
where empNbr in (select empNbr 
                 from Treats 
                 group by empNbr 
                 having count(*) >=2) ----- Ordered as a code

答案 2 :(得分:0)


克里斯托弗,
您可以使用以下查询来获得结果,

SELECT  t.empNbr, 
    e.Salary, 
    (e.Salary * e.count +(e.Salary/10) ) as NewSalary
from Treats t
INNER JOIN 
(SELECT empNbr, COUNT(*) AS count Employee GROUP BY empNbr) e
ON e.empNbr=t.empNbr
AND  e.count >=2
  

Explination

1
。我们可以在没有子句的情况下计算结果.2。在内部联接中,empNbr和派生员工的数量.3。在选择查询中使用此计数,当前工资乘以10%是加上薪水 希望这是你需要的。有任何问题,请随时询问