Rushi Khalkar Rushi Khalkar - 3 months ago 6
MySQL Question

how to get conditional column selection in SQL?

I'm trying to make a query that will give the appropriate column by user selection.

If user select cab:
i.e. where user_choice='cab'
Then it will give l.price_cab column

If user select seat:
i.e. where user_choice='price'
Then it will give l.price_seat column

Query:

SELECT l.company_name, l.price_seat, l.price_cab
from login l JOIN users u

Answer

You can use a CASE statement to return different columns based on criteria. Here's how you can do it:

SELECT
l.company_name,
CASE
    WHEN user_choice = 'cab' THEN l.price_cab
    WHEN user_choice = 'price' THEN l.price_seat
END as price
from login l JOIN users u