I can do something like this:
select
case a.x > 1 then a.bananas else a.pajamas end
from my_table a;
But when I try to tweak it like this:
select
case a.x > 1 then a.bananas, a.pajamas else a.strawberries, a.peaches end
from my_table;
it says I have an error in my syntax. How can I select arbitrary different subsets of my columns based on a condition?
You need a separate CASE
for each column:
SELECT
case a.x > 1 then a.bananas else a.pajamas end as bananas_or_pajamas,
case a.x > 1 then a.strawberries else a.peaches end as strawberries_or_peaches,
....
CASE is a function, and can only return a single value. You can only use it to switch the value of one field in a query. Another option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.
Using case:
SELECT
result1 = CASE
WHEN a.x > 1 THEN
a.bananas
ELSE
a.peaches
END from my_table a,
result2 = CASE
WHEN a.x > 1 THEN
a.pajamas
ELSE
a.strawberries
END from my_table a
Try this code:
SELECT
CASE
WHEN a.x > 1 THEN
a.bananas
ELSE
a.peaches
END from my_table result1,
CASE
WHEN a.x > 1 THEN
a.pajamas
ELSE
a.strawberries
END from
my_table result2;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.