1

运行 PostgreSQL 7.x(是的,我正在升级)

例子:

SELECT
    CASE 
        WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'group one'::text
        WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'group one'::text
        WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'group two'::text
        WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'group three'::text
        WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'group three'::text
        ELSE NULL::text
    END AS new_field,
    CASE 
        WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'subgroup a'::text
        WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'subgroup a'::text
        WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'subgroup a'::text
        WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'subgroup a'::text
        WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'subgroup b'::text
        ELSE NULL::text
    END AS another_new_field,...

有没有办法让一个case语句给出两个字段作为结果,因为处理的数据是相同的,只是标签不同。

4

1 回答 1

0

我不熟悉 Postgre,但也许您可以尝试使用通用表表达式来构建一个表,索引您的查找条件以及组和子组的输出结果,这可能看起来像这样(当然条件可能来自实际表也​​是...):

with Lookup as (
    select 0 as start, 3 as end,
        '01' as match, 'group one' as sgroup, 'subgroup a' as subgroup union
    select 0 as start, 4 as end,
        '123' as match, 'group one' as sgroup, 'subgroup a' as subgroup union
    select 0 as start, 5 as end,
        '4567' as match, 'group two' as sgroup, 'subgroup a' as subgroup union
    select 0 as start, 6 as end,
        '99999' as match, 'group three' as sgroup, 'subgroup a' as subgroup union
    select 0 as start, 3 as end,
        '07' as match, 'group three' as sgroup, 'subgroup b' as subgroup union
)
select
    L.sgroup as new_field,
    L.subgroup as another_new_field
from table T
left join Lookup L on "substring"(T."Field"::text, L.start, L.End) = L.match

然后您只需定义一次条件,并将它们匹配一次即可输出两个字段。正如@Tom 在评论中所表达的那样,这种场景在 SQL 中没有得到很好的处理,所以你会得到一个像上面这样更“hacky”的解决方案。

最好的祝福,

于 2011-09-12T18:13:46.420 回答