仅当其中一列 = 1 时,如何将列转换为行?

How do I convert columns to rows only if one of the columns = 1?

我正在按照本指南将列转换为 T-SQL 中的行:https://blog.devart.com/is-unpivot-the-best-way-for-converting-columns-into-rows.html

但是,只有当其中一列设置为 1 时,我才需要转换。

Table:

item    milk     peanut     soy
A       1        1          0
B       0        0          1
C       0        0          0

想要的结果:

item      allergen
A         milk
A         peanut
B         soy

请注意,我故意遗漏了项目 C。这是因为 none 的过敏原列是 1,因此在最后的 table 中不需要。我该如何实现?

您可以使用 cross apply 和过滤:

select t.item, v.allergen
from t cross apply
     (values ('milk', milk), ('peanut', peanut), ('soy', soy)
     ) v(allergen, flag)
where flag = 1;