简体   繁体   中英

Postgres CASE statement

I cant seem to make the CASE part work

SELECT ROUND((SUM((to_number(g.grade, '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2),    CASE WHEN g.grade='DRP' THEN '5.00' END
           FROM (grade g
             INNER JOIN registration r ON r.grade_id = g.grade_id)
             INNER JOIN subject s ON s.subjcode = r.subjcode
           WHERE g.grade NOT IN ('INC', 'W', 'INP') 
             AND r.sy = right(to_char(extract(year from now()- interval '1 year'),'9999'), 4)||'-'||right(to_char(extract(year from now()), '9999'),4)
             AND r.sem IN ('1', '2')
             AND r.studid='2012-0004'
           GROUP BY g.grade;

all I really want is to do is, if a student has a grade of DRP it'll automatically be counted as 5.0 so that the database could include DRP in calculating the GPA.

but it just says

ERROR:  invalid input syntax for type numeric: " "
********** Error **********

ERROR: invalid input syntax for type numeric: " "
SQL state: 22P02

currently using postgresql 9.3.2

The CASE part is ok (although you miss an ELSE there, it should still work and optionally return NULL).

The error is caused by the TO_NUMBER() function.

A case statement returns a value that has nothing inherently to do with any of the values that you fed into it. You seem to be thinking that your case statement will update the value of g.grade. It won't. I think what you want to do is use a case statement in place of the value for g.grade in your first function. Maybe:

SELECT ROUND((SUM((to_number((case when g.grade='DRP' then '5.00' else g.grade end), '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2)

I don't have a copy of Postgres handy so I can't test this, and I'm not familiar with the to_number function (it's been years since I used Postgres). But that's not the point of your question, so if that's not the correct way to call to_number, that's a different issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM