Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL subquery as usable variable

Tags:

sql

postgresql

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.

like image 395
jfreak53 Avatar asked Oct 03 '13 19:10

jfreak53


1 Answers

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
like image 145
Eric Hauenstein Avatar answered Sep 28 '22 11:09

Eric Hauenstein