You can do this using lead()
/ lag()
and aggregation:
select employee_id
from (select t.*,
lag(salary) over (partition by employee_id order by year) as prev_salary
from t
) t
group by employee_id
having min(salary - prev_salary) > 0 and
count(*) = 3;
This compares salaries in adjacent years and returns employees where the value is always increasing. It assumes that there are no gaps in the years -- as in your sample data.
The advantage of this approach is that you don't need to know the years in advance.
One option uses aggregation:
select employee_id
from mytable t
group by employee_id
having max(salary) filter(where year = 2020) > max(salary) filter(where year = 2019)
and max(salary) filter(where year = 2019) > max(salary) filter(where year = 2018)
This brings employee whose 2020 salary is greather than their 2019 salary, and whose 2019 salary is greater than their 2018 salary - which is how I understood your question.
I guess you don't want to hardcode the years in your query.
The best choice is the use of the window function LAG()
to get the salary of the previous 2 years, but you should also check that the 3 years that you check are consecutive:
SELECT DISTINCT employee_id
FROM (
SELECT *,
LAG(year, 1) OVER (PARTITION BY employee_id ORDER BY year) year1,
LAG(salary, 1) OVER (PARTITION BY employee_id ORDER BY year) salary1,
LAG(year, 2) OVER (PARTITION BY employee_id ORDER BY year) year2,
LAG(salary, 2) OVER (PARTITION BY employee_id ORDER BY year) salary2
FROM tablename t
)
WHERE year1 = year - 1 AND year2 = year - 2 AND salary > salary1 AND salary1 > salary2
If you want to check only for the current year and the 2 previous years then add 1 more condition in the WHERE
clause:
...AND year = strftime('%Y', CURRENT_DATE)
so you don't need to hardcode the current year,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.