以下是 WITH 语句的基本语法:
WITH cte_name (column1, column2, ...) AS (
-- CTE query definition
SELECT ...
)
-- Main query that references the CTE
SELECT ...
FROM cte_name;
其中:
- cte_name 是你为 CTE 分配的名称。
- (column1, column2, ...) 是可选的,用于为 CTE 的列指定名称,这在 CTE 中定义了列的别名。
- SELECT ... 是 CTE 的查询定义。
以下是一个简单的例子:
WITH department_avg_salary AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
SELECT * FROM department_avg_salary;
在这个例子中,department_avg_salary 是一个 CTE,它计算了每个部门的平均工资。在主查询中,我们可以引用这个 CTE,并选择它的结果。
CTEs 还可以嵌套,也可以在多个查询中共享。以下是一个更复杂的示例:
WITH high_salary_employees AS (
SELECT * FROM employees
WHERE salary > 80000
),
department_avg_salary AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
SELECT hse.employee_id, hse.first_name, hse.last_name, das.avg_salary
FROM high_salary_employees hse
JOIN department_avg_salary das ON hse.department = das.department;
在这个例子中,我们创建了两个 CTEs,一个用于选择高薪员工,另一个用于计算每个部门的平均工资。然后,我们在主查询中使用了这两个 CTEs,并通过 JOIN 将它们连接在一起。
WITH 语句是一个强大的工具,可用于提高查询的可读性和灵活性。
转载请注明出处:http://www.zyzy.cn/article/detail/14137/PostgreSQL