I have below PostgreSQL table, which is small sample of huge table
employee
emp_id | salary | rating | increment_year
--------------------------------------
28 3000 1 2023
25 2000 2 2023
30 1500 1 2021
28 1000 3 2022
32 1200 1 2023
23 1550 1 2023
30 2500 3 2022
30 3000 2 2023
I want make a PostgreSQL query which does
group by emp_id
and returns emp_id, sum(salary), get rating value based on latest increment_year, latest increment_year that was selected to get rating value
Example query result sample
emp_id | sum_salary | selected_rating_on_latest_increment_year | selected_increment_year_to_get_rating
------------------------------------------------------------------------------------------------------
28 4000 1 2023
value goes on for every emp_id
I have to use group by due to certain pre existing condition. So Doing it by group by, is something mandatory for me, if its possible.
Thanks in advance!
2
Answers
As a verbose alternative you may use a scalar subquery for
selected_rating_on_latest_increment_year
value instead of a JOIN. The rest would come from thet
CTE that does have agroup by
.DB-Fiddle