Reputation: 457
As an SQL newbie I have a question about selecting a column based on case values. The SQL below seems like it should work ok (at least to my extremely limited knowledge), but isn't. Any thoughts?
SELECT
tbl1.*,
CASE
WHEN tb11.col1 = "1" THEN tbl2.col1
WHEN tbl1.col1 = "2" THEN tbl2.col2
end as tbl2_col_select
FROM tbl1
LEFT JOIN tbl2
ON tbl1.id = tbl2.id AND
tbl1.year = tbl2.year
Thanks!
Upvotes: 0
Views: 263
Reputation: 69524
After reading your comments as I suspected you are returning different data types in different cases therefore you will need to cast it to a data type so in each case returned data type is the same,
One way you can handle this is to cast the data type to match the data types in each case, something like
SELECT tbl1.*
, CASE
WHEN tb11.col1 = '1'
THEN tbl2.col1
WHEN tbl1.col1 = '2'
THEN CAST(tbl2.col2 AS VARCHAR(100)) --<-- Data type of tbl2.col1
END AS tbl2_col_select
FROM tbl1
LEFT JOIN tbl2 ON tbl1.id = tbl2.id AND tbl1.year = tbl2.year
Upvotes: 1