Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the highest/lowest value from 2 columns

I’ve got this table:

  BP1             BP2
 -----------------------------
 140              80
 153              88
 90               162
 98               214
 98               69

I want to organize it into 2 columns: one of high BP and other of low BP:

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BP_High        BP_Low
---------------------------------
140             80
153             88
162             90
214             98
98              69

*all values are int

I’ve tried:

 SELECT CASE WHEN BP1 > BP2 THEN BP1
             WHEN BP1 < BP2 THEN BP2 END BP_High,
        CASE WHEN BP1 > BP2 THEN BP2
             WHEN BP1 < BP2 THEN BP1 END BP_Low 
FROM Table

and it does not work…it gives me all mixed up:

BP_High        BP_Low
---------------------------------
140             80
153             88
90             162
98             214
98              69

I’ve also tried:

 SELECT CASE WHEN BP1 > BP2 THEN BP1
             ELSE BP2 END BP_High,
        CASE WHEN BP1 > BP2 THEN BP2
             ELSE BP1 END BP_Low
 FROM Table 

Is there any other way then CASE WHEN to in order to get the highest/lowest value from 2 columns?

>Solution :

Your third attempt is almost correct, and you in fact can use CASE expressions here:

SELECT
    CASE WHEN BP1 > BP2 THEN BP1 ELSE BP2 END AS BP_High,
    CASE WHEN BP1 < BP2 THEN BP1 ELSE BP2 END AS BP_Low
FROM yourTable;

On other databases, such as MySQL, Postgres, or SQLite, there are LEAST() and GREATEST() scalar functions available. On those databases, your query can be simplified to:

SELECT
    GREATEST(BP1, BP2) AS BP_High,
    LEAST(BP1, BP2) AS BP_Low
FROM yourTable;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading