简体   繁体   中英

How can I iterate CASE statements in SQL?

I would like to write the a query in mySQL that has the following form:

SELECT *,
    CASE
        WHEN <column name> = 1  THEN 1
        ELSE 0
        END as "column_1",
    CASE
        WHEN <column name> = 2 THEN 1
        ELSE 0
        END as "column_2",
    CASE
        WHEN <column name> = 3 THEN 1
        ELSE 0
        END as "column_3"
    FROM <table name>;

I would like to write this query for a large number of cases (approximately 1000 cases), such that 1000 new columns are created that satisfy the conditions given above. How can I iterate this process in mySQL so that I don't have to write each line manually as I have done above (where there are only 3 cases)?

This may not be appropriate, but if you can live with one column of output (as a string rather than as multiple columns), then you might be able to do the following:

select t.id,
       group_concat( (case when t.column = v.value then '1' else '0' end) order by v.ordering) as string_flags
from (select 1 as ordering, 1 as value union all
      select 2, 2 union all
      . . .
     ) v cross join
     t
group by t.id;

This is just an idea. Performance is an issue, but it also gets around issues with the maximum number of columns in a row.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM