2011-09-12 128 views
1

運行PostgreSQL的7.x版(是的,我升級)CASE語句結果多個字段

例子:

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語句給兩個字段的結果作爲處理的數據是相同的,它只是不同的標籤。

+0

沒有具體很難肯定地說,但聽起來像是違反3NF的結構,如果兩個列的值的邏輯是相同的。也許不會,因爲你從兩個地方拉,但正如我所說,很難說。 –

+0

耶從一個來源拉,但一個是一個組,一個是一個小組,這個例子並沒有真正顯示這個 –

回答

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中處理得並不好,所以你只剩下一個像上面這樣更「黑客」的解決方案。

最好的問候,