Databases : understand how to organize and to use data

Relational Databases : Querying databases - aggregations and partitions operators

Relational databases : Querying with aggregations


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

Relational databases : Querying with aggregations (2)


SELECT count(*) FROM facilities

Relational databases : Querying with aggregations (3)


SELECT count(*) FROM facilities WHERE name LIKE 'Tennis%'

Relational databases : sorting and limiting data

Relational databases: example for ORDER BY

it can be combined with ASC and DESC to organize result in either ascending or descending order

SELECT * FROM members
ORDER BY joindate desc;

Relational databases: summarizing with group by

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

Relational databases : sub SELECTs

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

Relational databases : sub SELECTs with rank

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 

Query processing order

the example with RANK () OVER () shows an interesting fact about processing order