首页 > 解决方案 > 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...

标签: sqlpostgresqlcase

解决方案


我认为你的逻辑过于复杂了。你只需要选择你想要的列并给他们你想要的名字:

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_%'

推荐阅读