SQL Serise Part IV (SQL Subquery
2018-08-24 本文已影响0人
NoTKS
Subquery
SELECT DATE_TRUNC('day',createTime) AS day, col, COUNT(*) as new_col
FROM table
GROUP BY 1,2
ORDER BY 3 DESC;
# same result as above statement
SELECT *
FROM (SELECT DATE_TRUNC('day',createTime AS day,
col, COUNT(*) new_col
FROM table
GROUP BY 1,2
ORDER BY 3 DESC) sub;
# more complicated statement
SELECT SUM(total_col)
FROM table
WHERE DATE_TRUNC('month', createTime) =
(SELECT DATE_TRUNC('month', MIN(createTime)) FROM table);
SELECT AVG(avg_amount)
FROM (SELECT o.account_id, AVG(o.total_amount) avg_amount
FROM orders o
GROUP BY 1
HAVING AVG(o.total_amount) > (SELECT AVG(o.total_amount) avg_all
FROM orders o
JOIN accounts a
ON a.id = o.account_id)) temp_table;
WITH
WITH new_table AS (
SELECT DATE_TRUNC('day',createTime) AS day,
col, COUNT(*) as new_col
FROM table
GROUP BY 1,2)
SELECT channel, AVG(new_col) AS average_col
FROM new_table
GROUP BY 1
ORDER BY 2 DESC;