2016-09-07 38 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