在PostgreSQL中實(shí)現(xiàn)復(fù)雜查詢,可以使用子查詢、連接(JOIN)、聚合函數(shù)、窗口函數(shù)、CTE(公共表表達(dá)式)等技術(shù)
示例:查詢銷(xiāo)售額最高的產(chǎn)品。
SELECT product_name, sales
FROM products
WHERE sales = (SELECT MAX(sales) FROM products);
示例:查詢每個(gè)客戶的訂單總金額。
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;
示例:查詢每個(gè)產(chǎn)品類(lèi)別的平均價(jià)格。
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category;
示例:查詢每個(gè)部門(mén)的員工工資,并顯示其在部門(mén)內(nèi)的排名。
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;
示例:查詢銷(xiāo)售額最高的前三名產(chǎn)品。
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;
通過(guò)組合這些技術(shù),你可以在PostgreSQL中實(shí)現(xiàn)非常復(fù)雜的查詢。請(qǐng)根據(jù)實(shí)際需求選擇合適的技術(shù)。