简体   繁体   English

Redshift 在基于 CASE 语句的查询过程中将字符插入到字符串中

[英]Redshift Insert characters into a string during query based on CASE statement

I have a field with entries that can be 3 Letters 1,2 or 3 Numbers.我有一个字段,其中的条目可以是 3 个字母 1,2 或 3 个数字。 EG.例如。 AAA1 AAA01 AAA001 AAA1 AAA01 AAA001

I need to standardize the output in my query to always be 6 characters.我需要将查询中的输出标准化为始终为 6 个字符。

So I need a good case statement.所以我需要一个好的案例陈述。 Here is what I have tried.这是我尝试过的。

CASE WHEN LENGTH(field1) = 4 THEN LEFT(field1,3)||00||RIGHT(field1,1) WHEN LENGTH(field1) = 5 THEN LEFT(field1,3)||0||RIGHT(field1,2) ELSE field1 as field1

This always resulted in the AAA1 coming out as AAA01 instead of AAA001这总是导致 AAA1 出现为 AAA01 而不是 AAA001

I tried this hoping for a different result:我试过这个,希望得到不同的结果:

CASE WHEN field1 ~ '[A-Z]{3}[0-9]{1}' THEN LEFT(field1,3)||00||RIGHT(field1,1) WHEN LENGTH(field1) = 5 THEN LEFT(field1,3)||0||RIGHT(field1,2) ELSE field1 END AS field1

that did nothing right resulting in the fields that were already correct to be incorrect.没有做任何正确的事情导致已经正确的字段不正确。

So I messed with the REGEX and tried所以我弄乱了 REGEX 并尝试

CASE WHEN field1 ~ '^([A-Z]{3}[0-9]{1})$' THEN LEFT(field1,3)||00||RIGHT(field1,1) WHEN field1 ~ '^([A-Z]{3}[0-9]{2})$' THEN LEFT(field1,3)||0||RIGHT(field1,2) ELSE field1 END AS field1

which went right back to all the AAA1 resulting in AAA01 and the rest being correct.直接返回到所有 AAA1 导致 AAA01 和其余是正确的。

Now, I am doing a union and I am trying to dedupe the union as well with现在,我正在做一个工会,我也在尝试对工会进行重复数据删除

WHERE NOT EXISTS (SELECT table2.field3 FROM table2 WHERE table1.field3 = table2.field3 AND table2.field10 IS NOT NULL)

I can't give the entire query or data as they are confidential data, but any suggestions would be great.我不能提供整个查询或数据,因为它们是机密数据,但任何建议都会很棒。

I don't think you need any case statement or regex for this.我认为您不需要任何 case 语句或正则表达式。 This is what I came up with:这就是我想出的:

select left(field,3)||lpad(substring(field,4),3,'0')

The answer is that apparently 00 is not something that it likes.答案是显然 00 不是它喜欢的东西。

the following worked:以下工作:

CASE WHEN field1 ~ '^([A-Z]{3}[0-9]{1})$' THEN LEFT(field1,3)||0||0||RIGHT(field1,1) WHEN field1 ~ '^([A-Z]{3}[0-9]{2})$' THEN LEFT(field1,3)||0||RIGHT(field1,2) ELSE field1 END AS field1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM