在SQL中,当存储桶不一定是互斥的时,将数据存储到不同类别中的最佳方法是什么?
当使用normal case When语句时,数据被存储在它有资格的第一个类别中,而不会被考虑在case when语句的下面的其他存储桶中。我希望能够将数据存储到所有可能的类别中。
例如,假设我们有字符串'ABC‘。我想用存储桶“字符串包含A”,“字符串包含B”,“字符串包含D”来对这个字符串进行分类。我的代码类似于下面的代码:
Select case
when string like '%A%' then 'String_Contains_A'
when string like '%B%' then 'String_Contains_B'
when string like '%D%' then 'String_Contains_D'
else 'Other'
end as bucket,
String
from datatable
where string = 'ABC'根据我现在的理解,字符串'ABC‘似乎只会与存储桶' string _Contains_A’一起分类,而不会与'String_Contains_B‘一起分类。对存储桶'String_Contains_A‘和' string _Contains_B’下的字符串进行分类的最有效方法是什么?谢谢!
发布于 2017-08-08 04:07:08
联合查询将起作用
select 'bucket1' bucket, other fields
from etc
where whatever
union all
select 'bucket2' bucket, other fields
from etc
where whatever
etc发布于 2017-08-08 04:45:06
您可以使用标志而不是名称:
Select string,
(case when string like '%A%' then 1 else 0 end) as String_Contains_A,
(case when string like '%B%' then 1 else 0 end) as String_Contains_B,
(case when string like '%D%' then 1 else 0 end) as String_Contains_D
from datatable
where string = 'ABC';https://stackoverflow.com/questions/45554730
复制相似问题