sql - Postgres View:如何将所有列值分配给另一列CASE WHEN的值?
问题描述
我正在尝试创建一个视图,需要将“类别”列的所有值分配给“metric_type”,但出现错误。
我从中获取数据的表 LIN_Main_Followers
metric_name metric_type metric_value
likes function 65
shares country 101
likes SIZE_10001_OR_MORE 2
likes SIZE_11_TO_50 10
...and others
我想创建一个额外的列'category'并为其分配'metric_type'值,如果它像“SIZE_”一样的值。并将“company_size”值分配给“metric_type”列。
我的理想结果:
metric_name metric_type metric_value category
likes company_size 2 SIZE_10001_OR_MORE
likes company_size 10 SIZE_11_TO_50
查看代码
SELECT test.metric_name,
CASE WHEN test.metric_type LIKE 'SIZE_%' THEN test.category = test.metric_type ELSE test.category END,
CASE WHEN test.metric_type LIKE 'SIZE_%' THEN test.metric_type = 'company_size' ELSE test.metric_type END,
test.metric_type,
test.metric_value
FROM(SELECT lin.metric_name,
lin.metric_type,
lin.metric_value,
'Undefined'::text AS category
FROM "LIN_Main_Followers" lin
WHERE lin.metric_type LIKE 'SIZE_%') AS test
但我得到一个错误
ERROR: ERROR: CASE-Types text and boolean cannot be matched
LINE 2: CASE WHEN test.metric_type LIKE 'SIZE_%' THEN test.categ...
解决方案
我认为你的逻辑过于复杂了。你只需要选择你想要的列并给他们你想要的名字:
SELECT lin.metric_name, 'company_size' as metric_type,
lin.metric_value,
lin.metric_type as category
FROM "LIN_Main_Followers" lin
WHERE lin.metric_type LIKE 'SIZE_%'
推荐阅读
- flutter - 如何保存 TextField 用户输入
- javascript - 当项目有键时 Firebase 更新或添加值
- python - 两个集合不相等,但在转换为列表并转换回集合后相等
- java - 无法从 Firestore 获取数据
- c# - Task.Run vs Task.Factory.StartNew - 没有发生预期的死锁
- reactjs - 复选框更新值仅适用于 false 到 true,不适用于 true 到 false、React、mongoDB
- javascript - 从非反应类中使用反应路由器
- r - R:如何过滤列,只要它包含值的组合?
- amazon-web-services - 如何在 Appsync graphql 中为订阅者发布事件
- python - 根据对列中每个不同值具有特定条件的行计算 Pandas Dataframe 中的 perc