Sobes.tech
Senior

How to write a query to get a user with the second-to-last salary?

sobes.tech AI

Answer from AI

To get the user with the second-to-last salary, you can use an SQL query with a window function or a subquery. For example, if there is a table salaries with fields user_id, salary_date, and salary_amount, you can do it like this:

SELECT user_id, salary_amount
FROM (
    SELECT user_id, salary_amount,
           ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY salary_date DESC) as rn
    FROM salaries
) sub
WHERE rn = 2;

This query selects the second most recent salary for each user (the one before the last). In Go, you can execute this query using database/sql or an ORM to get the required data.

How to write a query to get a user with the… - sobes.tech