Skip to content
Advertisement

How to do a SQL query with SRFs and display only distinct values?

I’m trying to think about a way to do a query with a single row function and display only distinct values. Lets suppose that I have a table employees with the columns employee, store and salary and I want to use the SRF MAX(salary) to find out the best paid employee in each store. If there are more than 1 employee earning the MAX(salary) in one store, how can I avoid displaying more than 1 top earner per store? See the code below. The simpler the better. Thank you!

SELECT employee, emp1.store, emp1.salary
FROM employees emp1
INNER JOIN (SELECT store, salary, MAX(salary) FROM employees GROUP BY store) emp2
ON emp1.store = emp2.store
AND emp1.salary = emp2.salary

Advertisement

Answer

There is probably a cleaner way to do this:

    select * from 
    (
       SELECT employee, emp1.store, emp1.salary,
       ROW_NUMBER( ) 
       OVER ( partition by emp1.store order by emp1.salary desc ) rn
       FROM employees emp1
       INNER JOIN (SELECT store,  salary, MAX(salary) FROM employees GROUP BY store, salary) emp2
    ON emp1.store = emp2.store
    AND emp1.salary = emp2.salary
)
where rn = 1

Row_number() analytic function will assign a value of 1,2,3,… grouped by store. then you always just pick row 1 for each grouping.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement