2016-09-25 41 views
3

我試圖提高那些至少治療2名患者10%的員工的工資。我的問題是,薪水首先乘以他們治療的每位患者2,然後在最後乘以10%。例如,如果員工收入25.000和待遇3人,新薪水就變成82.500。SQL - 使用總和命令乘以同一人的工資

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 
+0

提供的樣本數據。 – p2k

回答

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我們需要的。然後我們選擇empNbrEmployeesalary和做數學:)

另一種方式:

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) 
+0

這工作完美,非常感謝你! – Christopher

+0

我的榮幸!我再添加一個解決方案,請嘗試一下。 – gofr1

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 
+0

我收到此錯誤:列'empNbr'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – Christopher

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.我們可以計算出的結果,而不having子句
2。在內部聯接中,empNbr和派生的該員工的計數
3.在select查詢中使用此計數,將當前工資乘以10%並加上工資 希望這是你需要的。任何問題,請隨時問