Relational Databases : Querying databases - aggregations and partitions operators
Databases can represent a very large volume of information, and we need to determine some aggregations (summaries) of data to handle them correctly in our "human" analysis. We may need to
SELECT count(*) FROM facilities
SELECT count(*) FROM facilities WHERE name LIKE 'Tennis%'
ORDER BY
allows to give an order based on a column sortRANK() OVER ()
allows to calculate a rank, and handles rank equalityit can be combined with ASC and DESC to organize result in either ascending or descending order
SELECT * FROM members
ORDER BY joindate desc;
the following will group bookings by memberid and count each group sub total bookings
SELECT bookings.memid as memberid, count(bookings.bookid) as cnt FROM bookings
LEFT JOIN members ON members.memid = bookings.memid
GROUP BY bookings.memid
ORDER BY cnt desc
One can consider using the result of a SELECT as a regular table
SELECT memberid, cnt, FROM (
SELECT bookings.memid as memberid, count(bookings.bookid) as cnt FROM bookings
LEFT JOIN members ON members.memid = bookings.memid
GROUP BY bookings.memid
ORDER BY cnt desc
) mem_bookings
One can consider using the result of a SELECT as a regular table
SELECT
memberid, cnt, pos
FROM (
SELECT
bookings.memid as memberid,
COUNT(bookings.bookid) as cnt
RANK () OVER (ORDER BY cnt desc) pos
FROM bookings
LEFT JOIN members ON members.memid = bookings.memid
GROUP BY bookings.memid
ORDER BY cnt desc
) mem_bookings
WHERE pos <= 4
the example with RANK () OVER ()
shows an interesting fact about processing order
FROM
--> WHERE
--> SELECT
SELECT
phase (the column is computed at this time), the WHERE
clause can't apply on it