2013-10-03 77 views
2

我想在稍後的另一個計算中使用出現在列中的子查詢。我怎樣才能做到這一點?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我需要這爲列計算過以後,也因爲它是自己的專欄。

+0

是上面查詢預計返回一行或多行? –

+0

多行,確切地說很多行。 – jfreak53

回答

2

我通常用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