SQL

More

Set theory

How to write SQL?

SELECT <columns>
FROM <table>
JOIN <other tables>
WHERE <filter condition>
GROUP BY <grouping>
HAVING <aggregate filter> # similar to where but works after aggregation done
ORDER BY <column list>
LIMIT <number of rows>
"""
Order of execution:
FROM + JOIN
WHERE
GROUP BY
HAVING 
SELECT 
DISTINCT
ORDER BY
LIMIT / OFFSET
"""
image
image
image

ROLLUP

image

CUBE

image

Window Functions

row_number(), rank(), dense_rank(), ntile(n)

percent_rank()

cume_dist()

image
  • 3 / 11 = 0.27
  • 5 / 11 = 0.45 because function will find other departments which have the number of headcounts less than or equal to 2. The result is 5.

first_value(), last_value()

lag(), lead()

  • LAG() and LEAD() just taking the others row's value
SuperMade with Super