Notion SQL Code
Notion SQL Code
SQL Code
SELECT
invoicedate,
-- STRing Format (Date)Time
STRFTIME("%Y", invoicedate) AS year,
STRFTIME("%m", invoicedate) AS month,
STRFTIME("%d", invoicedate) AS day,
STRFTIME("%Y-%m", invoicedate) AS monthid
FROM invoices
WHERE monthid = "2009-09"
Aggregate Functions
-- aggregate functions
SELECT
COUNT(*) AS total_songs,
ROUND(AVG(bytes),2) AS avg_bytes,
ROUND(SUM(bytes/(1024*1024)),2) AS sum_mb,
MIN(bytes) AS min_bytes,
MAX(bytes) AS max_bytes
FROM tracks;
SELECT
company,
COALESCE(company, "B2C") AS clean_company,
SQL Live 05 1
CASE
WHEN company IS NULL THEN "B2C"
ELSE "B2B"
END AS segment
FROM customers;
SELECT
CASE
WHEN company IS NULL THEN "B2C"
ELSE "B2B"
END AS segment,
country,
COUNT(*) AS num_customers
FROM customers
WHERE country IN ("Belgium", "France", "Italy")
GROUP BY 1,2
HAVING num_customers > 1
JOIN Tables
-- join syntax
SELECT
ar.name AS artist_name,
al.title AS album_name,
tr.name AS track_name
FROM artists AS ar
INNER JOIN albums AS al
ON ar.artistid = al.artistid -- pk=fk
INNER JOIN tracks AS tr
ON tr.albumid = al.albumid;
Aggregate + JOIN
-- join syntax
-- virtual table (VIEW)
CREATE VIEW genre_stats AS
SELECT
ge.name,
COUNT(*) as count_tracks,
AVG(milliseconds) AS avg_milliseconds
SQL Live 05 2
FROM artists AS ar
JOIN albums AS al ON ar.artistid = al.artistid
JOIN tracks AS tr ON tr.albumid = al.albumid
JOIN genres AS ge ON ge.genreid = tr.genreid
GROUP BY 1
ORDER BY 3 DESC
LIMIT 5;
-- subqueries
SELECT firstname, country
FROM (SELECT * FROM customers) AS sub
WHERE country = 'United Kingdom';
-- basic query
SELECT
firstname,
lastname,
email,
COUNT(*) count_order
FROM customers c
JOIN invoices i ON c.customerid = i.customerid
WHERE c.country = 'USA' AND STRFTIME("%Y-%m",i.invoicedate) = "2009-10"
GROUP BY 1,2,3;
-- with clauses
WITH usa_customers AS (
SELECT * FROM customers
SQL Live 05 3
WHERE country = 'USA'
), invoice_2009 AS (
SELECT * FROM invoices
WHERE STRFTIME("%Y-%m",invoicedate) = "2009-10"
)
-- standard subqueries
SELECT firstname, lastname, email, COUNT(*)
FROM (
SELECT * FROM customers
WHERE country = 'USA'
) AS t1
JOIN (
SELECT * FROM invoices
WHERE STRFTIME("%Y-%m",invoicedate) = "2009-10"
) AS t2
ON t1.customerid = t2.customerid
GROUP BY 1,2,3;
SQL Live 05 4