在PostgreSQL中實現復雜查詢,可以使用子查詢、連接(JOIN)、聚合函數、窗口函數、CTE(公共表表達式)等技術
示例:查詢銷售額最高的產品。
SELECT product_name, sales
FROM products
WHERE sales = (SELECT MAX(sales) FROM products);
示例:查詢每個客戶的訂單總金額。
SELECT c.customer_id, c.customer_name, SUM(o.amount) as total_amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name;
示例:查詢每個產品類別的平均價格。
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category;
示例:查詢每個部門的員工工資,并顯示其在部門內的排名。
SELECT e.employee_id, e.department_id, e.salary,
RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) as rank
FROM employees e;
示例:查詢銷售額最高的前三名產品。
WITH sales_ranked AS (
SELECT product_name, sales, RANK() OVER (ORDER BY sales DESC) as rank
FROM products
)
SELECT product_name, sales
FROM sales_ranked
WHERE rank <= 3;
通過組合這些技術,你可以在PostgreSQL中實現非常復雜的查詢。請根據實際需求選擇合適的技術。