how do i make a grading system using cases? - postgresql

pretty sure this is a pretty simple issue:
I need to create an exam results table for a student, but it needs to meet the conditions of If the student is awarded a grade of 70% or more then the result is to be shown as 'Distinction', a grade of at least 50% but less than 70% is to be shown as 'Pass' and grades below 50% are to be shown as 'Fail'. If the student has not taken the examination then the result is shown as 'Not taken'.
I'm having issues with my code which i can't seem to get right:
CREATE VIEW results_table
AS SELECT entry.excode, sname, student.sno, entry.egrade, result AS entry
FROM student
JOIN entry
ON student.sno = entry.sno
GROUP BY entry.excode, sname, student.sno, entry.egrade, result
SELECT result
CASE result
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade = NULL THEN 'Not Taken'
END;
ORDER BY entry.excode,sname
could somebody please tell me where i'm going wrong?

There are two types of SQL CASE statement, as documented for PostgreSQL here:
CASE WHEN condition THEN result ELSE default END
CASE expression WHEN value THEN result ELSE default END
The first form tests a series of (unrelated) conditions, and returns the result for the first one which is true, or the ELSE if none are. The second form is a short-hand for testing multiple conditions against a single value; CASE x WHEN y THEN 'y' WHEN z THEN 'z' END is short-hand for CASE WHEN x = y THEN 'y' WHEN x = z THEN 'z' END.
In your code, you're muddling the two syntaxes; you can't use the short-hand because you're doing something more complex than = in the conditions, so you need to leave out the word result:
CASE
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade IS NULL THEN 'Not Taken'
END
(Note: I've also changed = NULL to IS NULL, since no value is ever "equal to" NULL, because it means "we don't know what the value is equal to".)
You then need to put that into a SELECT query in the same place you'd select a normal column.
So starting from this simple query...
SELECT
entry.egrade as result
FROM
entry;
...you can put your CASE statement in like this:
SELECT
CASE
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade IS NULL THEN 'Not Taken'
END as result
FROM
entry;

Related

What did I do wrong? UPDATE with condition and LIKE postgres

There is a table and I need to update the data in the 3rd column, according to the condition. If there are brackets, then you need to take information from there, and if not, what is in the first column. Put it where there is no information on the 3rd column. In most cases it is necessary to put where status down or error
https://dbfiddle.uk/GgFft6cY
here is my request:
UPDATE table_1
SET name_3 =
CASE
WHEN name_3 != '' THEN name_3
WHEN name_1 LIKE '%(%' THEN SUBSTRING(name_1 FROM '%(%' FOR ')')
ELSE name_1
END
WHERE status IN ('down', 'error');
ERROR: invalid regular expression: parentheses () not balanced
what's wrong? or can it be done differently?
After FROM and FOR you need a start index and the length, which is a number.
UPDATE table_1
SET name_3 =
CASE
WHEN name_3 <> '' THEN name_3
WHEN name_1 LIKE '%(%' THEN SUBSTRING(name_1 FROM POSITION ('(' in name_1)+1 FOR POSITION (')' in name_1) -POSITION ('(' in name_1)-1)
ELSE name_1
END
WHERE status IN ('down', 'error');
Demo

how can use loop or IF in case when statements in postgresql

select distinct
x.vrgid, x.Weights, x.geom
from
(select
-- postcodes.id as postcodeid ,,fishnet.geom as geom
fishnet.gid as vrgid,
fishnet.geom as geom,
CASE WHEN
st_intersects(centroids.geom, urban.geom) and counts.nonurbancells != 0
THEN 0.95 :: numeric / counts.urbancells -------1st case
WHEN st_intersects(centroids.geom, urban.geom) and counts.nonurbancells = 0
THEN 1.00 :: numeric / counts.urbancells ---2ndcase
WHEN Not st_intersects(centroids.geom, urban.geom) = fishnet.gid :: boolean and counts.nonurbancells != 0
THEN 0.05 :: numeric / counts.nonurbancells ----3rd case
ELSE 0
END AS Weights
from vrg.urban_nonurban_count_new as counts
inner join vrg.gfk_2016_id_5_digit_pcd_areas2013_projected as postcodes on postcodes.id = counts.postid
right outer join vrg.rdsid_86_quadgrid_centroids as centroids on st_contains(postcodes.geom, centroids.geom)
left outer join vrg.rdsid86_quadgrid AS fishnet on fishnet.gid = centroids.gid
right outer join vrg.rdsid86_katrisk_poly_projected as urban on st_intersects(urban.geom, fishnet.geom)
where postcodes.id = '42395') as x
I have several case statements in my PL/Pgsql function in which the I get duplicate rows (with duplicate vrgids). Below is the query result
Here (the marked row) with id 7192 is the result of 1st case statement(refer the query)
What I would like to do is use loop or if condition to remove the vrgid and corresponding weights from the result once the 1st case statement is true.
So thet I won't get duplicate records. How is it possible?
May be I should use a condition in 3rd statement to result out the vrgids not present in 1st case statement.

unable to access case statement output from outer query.

I am trying to execute the following query in SSMS 2014. However, I am unable to access from the outer query, the column created using a case statement in the inner query. i.e.I am not able to access c.current.
Error obtained - Incorrect syntax near C
select C.trandate,C.plan,C.current from
(SELECT d.trandate,p.plan,
case when datediff(dd,trandate,getdate()) <=30 then d.amount else 0 end as 'Current',
case when datediff(dd,trandate,getdate()) between 31 and 60 then d.amount else 0 end as '31 to 60',
case when datediff(dd,trandate,getdate()) between 331 and 360 then d.amount else 0 end as '331 to 360',
case when datediff(dd,trandate,getdate()) > 360 then d.amount else 0 end as '>360',d.residentsys
FROM [HMXals_Reporting].[dbo].[TranARDetail] d
join [HMXals_Reporting].[dbo].[plans] p
on d.transys = p.plansys
) C
plan and current are both reserved keywords.
You'll have to go with
select C.trandate, C.[plan], C.[current] from
or choose other names.

need to translate specific t-sql case in pl/sql

Can anyone tell me how to translate the following T-SQL statement:
SELECT fileld1 = CASE
WHEN T.option1 THEN -1
ELSE
CASE WHEN T.option2 THEN 0
ELSE 1
END
END
FROM Table1 AS T
The point is I need to validate two different options from the table for a single field in the select statement..
I have tried to do somthing with an IF statement in pl/sql, but it just doesnt work for me:
SELECT IF T.option1 THEN -1
ELSE IF T.option2 THEN 0
ELSE 1
END
FROM Table1 AS T
I am not actually sure how to write IF statement inside the SELECT statement..
And also, I need to do it INSIDE the select statement because I am constructing a view.
Use:
SELECT CASE
WHEN T.option1 = ? THEN -1
WHEN T.option2 = ? THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
I can't get your original TSQL to work - I get:
Msg 4145, Level 15, State 1, Line 4
An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
...because there's no value evaluation. If you're checking if the columns are null, you'll need to use:
SELECT CASE
WHEN T.option1 IS NULL THEN -1
WHEN T.option2 IS NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
...or if you need when they are not null:
SELECT CASE
WHEN T.option1 IS NOT NULL THEN -1
WHEN T.option2 IS NOT NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
CASE expressions shortcircuit - if the first WHEN matches, it returns the value & exits handling for that row - so the options afterwards aren't considered.
If I remember correctly, PL/SQL also supports the case. You just would have to move the column alias from "field1=" before the expression to "AS filed1" after the expression.

How do I use T-SQL's Case/When?

I have a huge query which uses case/when often. Now I have this SQL here, which does not work.
(select case when xyz.something = 1
then
'SOMETEXT'
else
(select case when xyz.somethingelse = 1)
then
'SOMEOTHERTEXT'
end)
(select case when xyz.somethingelseagain = 2)
then
'SOMEOTHERTEXTGOESHERE'
end)
end) [ColumnName],
Whats causing trouble is xyz.somethingelseagain = 2, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.
SELECT
CASE
WHEN xyz.something = 1 THEN 'SOMETEXT'
WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
ELSE 'SOMETHING UNKNOWN'
END AS ColumnName;
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
declare #n int = 7,
#m int = 3;
select
case
when #n = 1 then
'SOMETEXT'
else
case
when #m = 1 then
'SOMEOTHERTEXT'
when #m = 2 then
'SOMEOTHERTEXTGOESHERE'
end
end as col1
-- n=1 => returns SOMETEXT regardless of #m
-- n=2 and m=1 => returns SOMEOTHERTEXT
-- n=2 and m=2 => returns SOMEOTHERTEXTGOESHERE
-- n=2 and m>2 => returns null (no else defined for inner case)
If logical test is against a single column then you could use something like
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
More information - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017