I am a new sql learner. I am stuck with the following problem:
Suppose I have the following table :
ID | detail |
---|---|
A1 | 11 |
A1 | 12 |
A1 | null |
A1 | 0 |
A2 | 11 |
A2 | 13 |
Now I want to create a new table with two columns ID and result (say), where each ID appears once. If any row corresponding to an ID has 12 in the detail column, then result = 1, else 0. So basically my result should be the following table:
ID | detail |
---|---|
A1 | 1 |
A2 | 0 |
My attempt to solve this was:
insert into new_table select ID, (select detail,
(case
when detail = 12 then '0'
else '1'
end) as new_column from table)
from table;
But this piece of code is giving me error : operand should contain 1 column. I do not know how to approach this problem. Please help me understand how to solve this. I am trying this in MySql.
3
Answers
Use a CTAS statement for the creating the table, and use a case expression with aggregation.
You don’t need a subquery. You can make the expression directly in the select-list.
Use GROUP BY to make the result have one row per value of ID.
EXISTS
will return only the correct scalar value and it will be fastfiddle