2016-09-07 109 views
2

我正嘗試使用SQL select表達式將以下內容從第1列轉換爲第2列。將數字代碼轉換爲從右至左的字符串

Code  Outcome 
88881133 Species 1, 2, 3, 4 sick 
88888888 NULL 
88888833 Species 1, 2 sick 
88888811 Species 1, 2 sick 
88888111 Species 1, 2, 3 sick 
88888881 Species 1 sick 

代碼應該從右到左讀取。
1或3表示物種生病。
8表示物種沒有病。

我想這涉及到一些CASE表達式,但我不能走得很進一步比:

SELECT 
CASE WHEN RIGHT(Code, 1) = 1 OR WHEN RIGHT(Code, 1) = 3 
THEN 'Species 1 sick' END AS Outcome 
FROM table 

我使用Vertica的數據庫

回答

1

這裏只是用likecase另一種方法。我只是將1和3翻譯爲1,將8翻譯爲0.主要是因爲我打算採用二進制方法,但這看起來更簡單。真正的原因只是保持簡單的陳述(否則你必須檢查1和3個案例)。

rtrim有第二個參數,意思是隻修剪額外的逗號空間。刪除最後一個是一個簡單的技巧。外殼只是確保有物種(否則它會返回null)。

希望它有幫助。

with translated_mytable as (
    select code, translate(code,'813','011') newcode 
    from mytable 
) 
select Code, 
     case when newcode like '%1%' then 
     'Species ' || 
     rtrim(case when newcode like '_______1' then '1, ' else '' end || 
       case when newcode like '______1_' then '2, ' else '' end || 
       case when newcode like '_____1__' then '3, ' else '' end || 
       case when newcode like '___ 1___' then '4, ' else '' end || 
       case when newcode like '___1____' then '5, ' else '' end || 
       case when newcode like '__1_____' then '6, ' else '' end || 
       case when newcode like '_1______' then '7, ' else '' end || 
       case when newcode like '1_______' then '8, ' else '' end, 
     ', ') || ' sick' 
     end Outcome   
from translated_mytable 
+0

你好,你的腳本似乎只捕獲'1'。我該如何修改它,以便我可以同時使用'1'和'3'來表示生病呢? (對不起,我發佈了這個更早但顯然它沒有通過) – Jake

+0

@Jake如果你仔細觀察,我將1和3翻譯爲1,以使相似的情況條件更簡單。看看newcode。 0不生病,1生病。 – woot

+0

哦,謝謝!讓我先嚐試吸收,對我來說很多新東西:) – Jake

1

請嘗試查詢 - 它應該做的伎倆 - 請只是改變t_tabyour_table_name,它應該工作

WITH 
t_tab2 AS 
(
SELECT t.code, 
     CASE WHEN SUBSTR(t.code,1,1) IN (1,2,3) THEN 8 END Out1, 
     CASE WHEN SUBSTR(t.code,2,1) IN (1,2,3) THEN 7 END Out2, 
     CASE WHEN SUBSTR(t.code,3,1) IN (1,2,3) THEN 6 END Out3, 
     CASE WHEN SUBSTR(t.code,4,1) IN (1,2,3) THEN 5 END Out4, 
     CASE WHEN SUBSTR(t.code,5,1) IN (1,2,3) THEN 4 END Out5, 
     CASE WHEN SUBSTR(t.code,6,1) IN (1,2,3) THEN 3 END Out6, 
     CASE WHEN SUBSTR(t.code,7,1) IN (1,2,3) THEN 2 END Out7, 
     CASE WHEN SUBSTR(t.code,8,1) IN (1,2,3) THEN 1 END Out8 
FROM t_tab t 
) 
SELECT tt.code, 
     CASE WHEN tt.out1||tt.out2||tt.out3||tt.out4|| 
       tt.out5||tt.out6||tt.out7||tt.out8 IS NULL THEN NULL 
      ELSE REGEXP_REPLACE(
       REGEXP_REPLACE(RTRIM('Species' || ' ' || tt.out8 || ', ' || tt.out7|| ', ' 
                 || tt.out6 || ', ' || tt.out5 || ', ' 
                 || tt.out4 || ', ' || tt.out3 || ', ' 
                 || tt.out2 || ', ' || tt.out1, ', ') 
                 || ' sick', ', | ,', ','), ',{1,}', ', ') END AS Outcome 
FROM t_tab2 tt 

它給我的結果:

1 88881133 Species 1, 2, 3, 4 sick 
2 88888888  
3 88888833 Species 1, 2 sick 
4 88888811 Species 1, 2 sick 
5 88888111 Species 1, 2, 3 sick 
6 88888881 Species 1 sick 
+0

哇,讓我試着消化和回來,多謝提前! – Jake

+0

Enjoi!請讓我知道它是否適合你。 – massko