-1

the table data like this, how to compare 0 is greater than null, and get the greatest value ?

id score_a score_b
1 0 null
2 null null
3 1 0

I want the result like this

id max_score
1 0
2 null
3 1

I tired this, but the result is unexpected

SELECT greatest(coalesce(score_a,0),coalesce(score_b,0)) as max_score FROM table
id max_score
1 0
2 0
3 1
kenken9999
  • 765
  • 1
  • 6
  • 14

1 Answers1

0

Use a CASE expression:

SELECT CASE 
         WHEN COALESCE(score_a, score_b) IS NULL THEN NULL
         ELSE GREATEST(COALESCE(score_a, 0), COALESCE(score_b, 0)) 
       END max_score 
FROM tablename

See the demo.
Results:

max_score
0
null
1
forpas
  • 160,666
  • 10
  • 38
  • 76