Reputation: 155
Please help to solve the following issue. I've table called time_schedule.
My Requirement is if start_city_name='somecity' then I need select departure_time
else I need to select arrival_time. Here I want to which one is selected. For ex:
SELECT IF(start_city_name='somecity',departure_time,arrival_time)
FROM time_schedule;
here if condition is matched departure_time is selected. Then I need to select it as departure_time.
else if condition is failed arrival_time is selected,then I need to select the result as arrival_time. I'm Using MySQL. Thanks in Advance.
Upvotes: 4
Views: 25891
Reputation: 55649
To know which one is selected, you can do something like this:
SELECT IF(start_city_name='somecity', 'Departure time', 'Arrival time'),
IF(start_city_name='somecity', departure_time, arrival_time)
FROM time_schedule;
You can't really have it as the column name, what if there's one row where the condition is true and one where the condition is false, what should the column name be?
However, if you're happy splitting them into 2 columns:
SELECT IF(start_city_name='somecity', NULL, arrival_time) AS 'Arrival time',
IF(start_city_name='somecity', departure_time, NULL) AS 'Departure time'
FROM time_schedule;
This is very similar to simply saying:
SELECT arrival_time, departure_time
FROM time_schedule;
Except that arrival_time
will be NULL
when the condition is true, and departure_time
will be NULL
when the condition is false.
Upvotes: 9
Reputation: 8816
Use a CASE
construct like this:
SELECT CASE start_city
WHEN 'somecity' THEN departure_time
ELSE arrival_time
END AS column_alias
FROM time_schedule;
Google for CASE
statements for more details. There are plenty of resources on this.
Upvotes: 1