开发者

How to incorporate the next result of a query in the query in PostgreSQL?

开发者 https://www.devze.com 2023-04-04 16:41 出处:网络
Suppose you have a students table: UIDGradeLevel ------------------ 1Pass21 2Fail25 3Pass23 4Fail22 5Pass25 How would you write a Postgres SQL query that:

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:

  1. Orders the students by ascending level
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消