6

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

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我需要这个作为一个列来计算出来,也作为它自己的列。

4

1 回答 1

9

我通常使用公用表表达式来执行此操作。

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
于 2013-10-03T20:12:32.603 回答