Sql-server – Finding the total sum of salary for person who worked at least two years

sql server

Employee table

enter image description here

So, I am looking for a result with Name, salary and age – Salary should be the sum of all he earned, also it should be calculated only for person who has worked more than a year

For Example employee Sunny worked totally 4 years whereas Arpita worked only one year

I tried group by name and calculated totally earning but not able to find only for person who worked for more than a year, I mean at least two years

select name as [Name of Employee], sum(salary) as [Salary Earned] from Employee group by name;

Best Answer

Try this:

SELECT name AS [Name of Employee], 
    SUM(salary) AS [Salary Earned] 
FROM Employee 
GROUP BY name
HAVING MAX(year) > 1;

This will exclude those records whose maximum "year" having is 1, basically those who have not been employed for more than 1 year.