Reputation: 23
I'm looking for SQL query for a problem that I have.
I have 2 columns - the first is "employee full name" (containing FULL name) and the second is "Hours".
Employee Full Name | Hours | grading
-------------------------------------
john ran 122
john medi 177
john mat 138
jack rom 66
jack ton 88
I would like to update the database with the "grading" column in the following way:
grouping employees by their FIRST name, and then grading them (in ascending order) by working hours (highest working hours for employee with a specific first name) gets grade of 1, second 2, etc...).
The result should be like this:
Employee Full Name | Hours | grading
------------------------------------
john ran 122 3
john medi 177 1
john mat 138 2
jack rom 66 2
jack ton 88 1
There are no 2 employees with the same full name
Upvotes: 2
Views: 187
Reputation: 247630
You can use a CTE
to perform this update using row_number()
;with cte as
(
select *,
row_number()
over(partition by substring([EMPLOYEE FULL NAME], 1, charindex(' ', [EMPLOYEE FULL NAME]))
order by hours desc) rn
from yourtable
)
update cte
set grading = rn;
Ideally, you will want to normalize your database to have the first and last name in separate columns.
Upvotes: 3