2015-05-25 92 views
0

考慮我有2名僱主(谷歌,雅虎)和谷歌是具有3個員工和雅虎是2員工SQL查詢更改行值

我的查詢應該添加

1000 to employee1 for google company 
2000 to employee2 for google company 
3000 to employee3 for google company 

1000 to employee1 for Yahoo company 
2000 to employee2 for Yahoo company 

對於每一組員工的它應該增加工資從1000

回答

1

您可以使用ROW_NUMBER()來計算新的工資開始:

SELECT Company, 
     Emp, 
     ROW_NUMBER() OVER(PARTITION BY Company ORDER BY Emp) * 1000 + Salary As NewSalary 
FROM YourTable 

如果要實際更新工資,則有一種方法是將該查詢用作CTE

;WITH CTE AS ( 
SELECT Company, 
     Emp, 
     ROW_NUMBER() OVER(PARTITION BY Company ORDER BY Emp) * 1000 + Salary As NewSalary 
FROM YourTable 
) 

UPDATE T 
SET Salary = NewSalary 
FROM YourTable T 
INNER JOIN CTE C ON(T.Company = C.Company AND T.Emp = C.Emp)