PostgreSQL子查询作为可用变量

时间:2013-10-03 19:48:57

标签: sql postgresql

我正在尝试使用稍后在另一个计算中出现在列中的子查询。我怎么能这样做?

SELECT c_id, c_title, c_enrolcap,
(SELECT COUNT(e_id) AS enrol FROM enrollments WHERE e_c_id = c_id) AS enrolled,
c_enrolcap - enrolled AS avail,
FROM classes AS c

基本上来自enrolled的内容我需要将此作为一个列来计算以后的列,也可以作为它自己的列。

1 个答案:

答案 0 :(得分:3)

我通常使用Common Table Expressions执行此操作。

http://www.postgresql.org/docs/9.3/static/queries-with.html

在外部查询中执行c_enrolcap - enrolled as avail

像:

WITH enrollment AS (
SELECT c_id, c_title, c_enrolcap,
(SELECT COUNT(e_id) AS enrol FROM enrollments WHERE e_c_id = c_id) AS enrolled

FROM classes AS c)
SELECT c_id, c_title, c_enrolcap, enrolled, c_enrolcap - enrolled AS avail
FROM enrollment