Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case when then, but with AND condition inside when and before then

In the below query I want to add an AND condition inside the CASE's WHEN and before THEN is that possible?

for example WHEN 'r' AND table1.name="jones" THEN 'very high'

SELECT table1.id, table1.name,
   CASE table1.event
     WHEN 'r' THEN 'very high'
     WHEN 't' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
like image 989
Anisoropos Avatar asked Sep 03 '11 18:09

Anisoropos


People also ask

Can you have multiple conditions in a case statement?

Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.

Can we use and condition in case statement in SQL?

CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component. You can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN . This includes stringing together multiple conditional statements using AND and OR .

Can we use aggregate function in case statement?

CASE statement in SQL and aggregate functions Aggregate functions in SQL Server perform calculations and return a single value. Examples of aggregate functions are MIN, MAX, COUNT, ABG and CHECKSUM. For this purpose, we use the COUNT aggregate function in SQL Server.


2 Answers

You can rewrite your statement like this to accomplish what you want

SELECT table1.id, table1.name,
   CASE 
     WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
     WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
     ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
           ORDER BY table2.value DESC LIMIT 1)
   END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC

notice that you need to remove table1.event after the CASE statement. documentation here

like image 170
Brian Glaz Avatar answered Sep 25 '22 08:09

Brian Glaz


Anything that evaluates to a boolean (true or false) can go in the WHEN condition of a CASE statement. So you can replace 'r' with:

('r' AND table1.name='jones')

Thinking about this more, you might have to lose the table1.event after CASE

SELECT table1.id, table1.name,
    CASE 
        WHEN (table1.event = 'r' AND table1.name='Jones') THEN 'very high'
        WHEN table1.event = 't' THEN 'very low'
        ELSE (SELECT table2.risk 
              FROM table2 
              WHERE table2.value <= table1.value 
              ORDER BY table2.value DESC LIMIT 1)
    END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
like image 44
Josh Darnell Avatar answered Sep 23 '22 08:09

Josh Darnell