简体   繁体   English

如何在SQL中迭代CASE语句?

[英]How can I iterate CASE statements in SQL?

I would like to write the a query in mySQL that has the following form: 我想在mySQL中编写具有以下形式的查询:

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. 我想针对大量情况(大约1000个情况)编写此查询,以便创建满足上述条件的1000个新列。 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)? 如何在mySQL中迭代此过程,这样就不必像上面所做的那样手动编写每一行(这里只有3种情况)?

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. 性能是一个问题,但同时也解决了连续的最大列数问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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