・例えば、組織図の階層構造を解決して、特定の部に紐づく課の売上を集計するといったことができる。
実装例
WITH regional_sales AS (
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
), top_regions AS (
SELECT region
FROM regional_sales
WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales)
)
SELECT region,
product,
SUM(quantity) AS product_units,
SUM(amount) AS product_sales
FROM orders
WHERE region IN (SELECT region FROM top_regions)
GROUP BY region, product;
参考
https://www.sraoss.co.jp/tech-blog/pgsql/pg12-cte/
https://www.postgresql.jp/document/9.5/html/queries-with.html