OVER and PARTITION BY

OVER and PARTITION BY are window functions that allow calculations to be done over a set of rows. Unlike aggregate functions, window functions do not group the results though. In order to better understand these two window functions, let's take the time to run the following query in the phpMyAdmin web interface:

SELECT DISTINCT superior AS manager_id, (SELECT last_name FROM employees WHERE id = manager_id) AS last_name, SUM(salary) OVER(PARTITION BY superior) AS 'payroll per manager'
FROM employees
WHERE superior IS NOT NULL
ORDER BY superior;

After running this query, you should see the following result:

List of managers with payroll per manager

As we can see, the result set shows the payroll per manager column without grouping the results. This is why we had to use the DISTINCT statement in order to avoid having multiple rows for the same manager. Obviously, window functions allow for efficient querying and optimized performance when doing aggregate calculations on subsets of rows that have some sort of relationship to the current row.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset