類似mssql中的臨時表變量一樣,在postgresql 中可以使用with 來定義臨時表變量
WITH regional_sales AS ( --reginal_sales 是臨時表變量的表名
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;
補充:使用臨時表變量查詢,可以使代碼更清晰,並且避免編寫重復的代碼.