How to incorporate the next result of a query in the query in PostgreSQL?
Suppose you have a students table:
UID Grade Level
------------------
1 Pass 21
2 Fail 25
3 Pass 23
4 Fail 22
5 Pass 25
How would you write a Postgres SQL query that:
- Orders the students by ascending level
- Calculates the percentage of students at the next level that have passed
So, in this case:
Level % Passed at next level
-------------------------------------
21 开发者_开发技巧 0%
22 100%
23 50%
25 -
Working in Postgres 8.3.
Thanks.
This should work:
SELECT *
FROM
(
SELECT (SELECT max(level) FROM students "inner" WHERE "inner".level < "outer".level) as Level
, sum(Case When grade = 'Pass' Then 1.0 Else 0.0 End) / count(*) as Percentage
FROM students "outer"
GROUP BY level
union all
SELECT max(level) as Level
, null as Percentage
FROM students
) mylevels
WHERE level is not null
But this is not a pretty code.
I recommend you to create a table level(level int, next_level int) the code would be much more simple.
精彩评论