Rushi Khalkar Rushi Khalkar - 1 year ago 75
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


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

Answer Source

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

    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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download