如何将雪花中单词的第一个字母大写?

时间:2021-03-11 19:10:59

标签: sql string snowflake-cloud-data-platform

我需要在 Snowflake 的 SQL qwery 中将某些单词的首字母大写。

我目前正在使用此功能:

SELECT ...
    case when FLAG1 is null then upper(FLAG2) else FLAG1 END as STATUS,
...;

然而,UPPER() 函数将我所有的 FLAG2 单词呈现为完全大写。有谁知道雪花中单词的首字母大写吗?

2 个答案:

答案 0 :(得分:3)

使用initcap()函数,它返回输入字符串(expr),每个单词的第一个字母大写,后面的字母小写。

如果只希望字符串中的第一个字母大写,忽略单词分隔符(即输入表达式被视为单个连续单词),请指定空字符串作为分隔符参数

INITCAP( str, '')

答案 1 :(得分:1)

SELECT column1, IFF(column1, UPPER(SUBSTRING(column2,1,1)) || LOWER(SUBSTRING(column2,2)), column2) 
FROM VALUES 
    (true,'all_lower'),
    (true, 'ALL_UPPER'),
    (true, 'mIxEd'),
    (false,'all_lower'),
    (false, 'ALL_UPPER'),
    (false, 'mIxEd');

可以拆开一点看看工作中的零件。

SELECT column1 as flag
     ,column2 as orig
     ,UPPER(SUBSTRING(column2,1,1)) || LOWER(SUBSTRING(column2,2)) as first_upper
     ,IFF(flag, first_upper, orig)
FROM VALUES 
    (true,'all_lower'),
    (true, 'ALL_UPPER'),
    (true, 'mIxEd'),
    (false,'all_lower'),
    (false, 'ALL_UPPER'),
    (false, 'mIxEd');

给出:

FLAG    ORIG        FIRST_UPPER   IFF(FLAG, FIRST_UPPER, ORIG)
TRUE    all_lower   All_lower     All_lower
TRUE    ALL_UPPER   All_upper     All_upper
TRUE    mIxEd       Mixed         Mixed
FALSE   all_lower   All_lower     all_lower
FALSE   ALL_UPPER   All_upper     ALL_UPPER
FALSE   mIxEd       Mixed         mIxEd