Reputation: 2369
I'm trying to use a subquery that comes out into a column in another calculation later on. How can I do this?
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
So basically what comes out of enrolled
I need this as a column to calculate off of later and also as it's own column.
Upvotes: 10
Views: 14613
Reputation: 2565
I usually do this with Common Table Expressions.
http://www.postgresql.org/docs/9.3/static/queries-with.html
Do the c_enrolcap - enrolled as avail
in the outer query.
Like:
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
Upvotes: 12