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?
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