在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中实现非常复杂的查询。请根据实际需求选择合适的技术。