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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With