10

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.

2
  • Is the above query expected to return a single row or multiple rows? Commented Oct 3, 2013 at 20:00
  • Multiple rows, many rows to be exact. Commented Oct 3, 2013 at 20:06

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.