sql - 将 bool 反馈列替换并压缩为 BigQuery 中的单个分数列

标签 sql google-bigquery case

我的数据如下所示(注意每行一个 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/

相关文章:

java - 如果子查询的结果集列值为 NULL,则显示某个值

sql - 有没有办法简化这个 TSQL Case 语句?

sql - SQL Server 数据库 'optimizing' 索引的奇怪结果,原因是什么?

design-patterns - 为什么使用 Gcloud Pub/Sub?

google-bigquery - Google 大查询 UTC_USEC_TO_DAY/WEEK/MONTH/YEAR

google-analytics - GA360 导出到 Bigquery

sql - Laravel Eloquent 选择 CASE?

c# - 将 SQL 列中的项目与数组进行比较

mysql - 具有多个外键的表在mysql中加入1个外键

sql - 如何更新作为组合键的一部分并在oracle SQL中充当一个表的主键和其他表中的外键的列