skip to Main Content

I’m working on my first SQL case statement – and unsure how to do this. I have two different columns of data, one is for drive A, the other drive B. I want to select data from drive A for display when drive A is active, and display data from drive B when it is active. I’m having trouble understanding how to use the case statement as a part of the select statement.

I know that the case statement returns a boolean value, but I’m unsure of how to incorporate this into my Select expression. Right now I have:

SELECT t_stamp AS DateTime, 
    CASE WHEN DriveAActive 
         THEN DriveA_TorqueActual 
         ELSE DriveB_TorqueActual

I don’t see a good reference on this topic – any pointers?

2

Answers


  1. Mysql CASE statement is simple and syntax like:

    CASE
       WHEN condition_1 THEN result_1
       WHEN condition_2 THEN result_2 
       ... ... ...
       WHEN condition_m THEN result_m
       ELSE result_n
    END AS column_name
    

    Your question is not clear. According to question there are two columns DriveA & DriveB. Need to display data which one is ‘Active’.

    I think DriveA has high priority. So, design code as follows:

      SELECT
          t_stamp AS DateTime, 
          CASE 
              WHEN(DriveA = 'Active')
                THEN DriveA_TorqueActual 
              WHEN(DriveB = 'Active')
                THEN DriveB_TorqueActual
              ELSE NULL
          END AS ACTIVE_DRIVE
      FROM SQL_TABLE
    

    OR

      SELECT
          t_stamp AS DateTime, 
          CASE 
              WHEN(DriveA = 'Active' AND DriveB = 'Active')
                THEN result1
              WHEN(DriveA = 'Active' AND DriveB <> 'Active')
                THEN result2
              WHEN(DriveA <> 'Active' AND DriveB = 'Active')
                THEN result3
              ELSE result4
          END AS ACTIVE_DRIVE
      FROM SQL_TABLE
    
    Login or Signup to reply.
  2. I believe you are missing a closing END keyword to the CASE statement in your sql query. Also, as mentioned by the other user that’s answered above, The question is quite ambigous as one does not know which of the columns have priority over the other should both columns i.e columns DriveA and DriveB both be active at the same time. In any case, if only one column can be active at a time then the code below would suffice. Else, you would have to adjust the conditions within each WHEN statement to cater for that scenario.

    SELECT t_stamp AS DateTime, 
        CASE WHEN DriveAActive 
             THEN DriveA_TorqueActual 
             ELSE DriveB_TorqueActual
        END AS alias
    FROM table_name
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search