Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine values in table

Tags:

sql

sqlite

The database has the schema students(name TEXT, score INTEGER), and there is a table called grades:

Grade   MIN_score    MAX_score
A       4            5
B       3            4
C       2            3

I want to select the names of all students and their grades according to the table, and turn A and B to 'pass' in the resulting table.

Below is my partial solution without turning A and B to 'pass' in the resulting table, and I wonder how to achieve that additional function.

SELECT name, grade
FROM students 
LEFT JOIN grades 
ON grade BETWEEN MIN_score and MAX_score;
like image 590
Vladimir Avatar asked Jan 21 '26 13:01

Vladimir


2 Answers

Don't use between. You'll get duplicates.

select s.name, s.score,
       (case when g.grade in ('A', 'B') then 'Pass' end) as status
from students s join
     grades g
     on s.score > g.MIN_score and s.score <= MAX_score;

You need to be very careful about the join condition so a score of "4" is not treated as both an "A" and a "B" (as between would do).

like image 50
Gordon Linoff Avatar answered Jan 23 '26 03:01

Gordon Linoff


You need to use case when expression, e.g.:

select case when grade in ('A', 'B') then 'Pass' else '' end

I believe you query should be something like this:

select name, score, case when grade in ('A', 'B') then 'Pass' else '-' end
from students
join grades on score between MIN_score and MAX_score
like image 38
Kirill Polishchuk Avatar answered Jan 23 '26 03:01

Kirill Polishchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!