我的数据如下所示(注意每行一个 TRUE):
''''''''''''''''''''''''''''''''''''''''''''''''''''''''
|ROWS| very_good | good | neither | poor | very poor |
''''''''''''''''''''''''''''''''''''''''''''''''''''''''
| 1 | TRUE | FALSE | FALSE | FALSE | FALSE |
| 2 | FALSE | TRUE | FALSE | FALSE | FALSE |
| 3 | FALSE | FALSE | FALSE | TRUE | FALSE |
|... | ... | ... | ... | ... | ... |
我想将每个 TRUE 替换为一个数字,该数字取决于它所在的列 (5-1),因此 very_good
的分数为 5,very_poor
为 1,然后将其压缩到一列中。所以它看起来像这样:
''''''''''''''
|ROWS| SCORE |
''''''''''''''
| 1 | 5 |
| 2 | 4 |
| 3 | 2 |
|... | ... |
到目前为止我已经尝试过:
SELECT
...,
(REPLACE(CAST(very_good = 'true' AS STRING),'true', '5'),
REPLACE(CAST(good = 'true' AS STRING),'true', '4'),
REPLACE(CAST(neither = 'true' AS STRING),'true', '3'),
REPLACE(CAST(poor = 'true' AS STRING),'true', '2'),
REPLACE(CAST(very_poor = 'true' AS STRING),'true', '1')) AS SCORE,
...,
FROM table
但这会创建多个列,并且我找不到在单个列中执行多个 REPLACE 的方法,此外,这不会更改需要删除的 FALSE。理想情况下,我还需要处理一些填充空值的行。
最佳答案
您可以使用case
表达式:
select
rows,
case
when very_good = 'true' then 5
when good = 'true' then 4
when neither = 'true' then 3
when poor = 'true' then 2
when very_poor = 'true' then 1
end as score
from mytable
请注意,为了使这一点有意义,每行中只有一列应该为 true - 否则,case
表达式将返回得分最高的列。
如果列的数据类型为boolean
,以下内容也可能适用于 Big Query:
select
rows,
case
when very_good then 5
when good then 4
when neither then 3
when poor then 2
when very_poor then 1
end as score
from mytable
关于sql - 将 bool 反馈列替换并压缩为 BigQuery 中的单个分数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63855191/