代码之家  ›  专栏  ›  技术社区  ›  Philip

使用STRING_AGG在文本周围放置引号

  •  1
  • Philip  · 技术社区  · 3 年前

    我有以下带有样本数据的查询

    select  
        (
            SELECT  STRING_AGG(TRIM(innerAgg.Result), '" - "')
            FROM
            (
                SELECT  DISTINCT
                    value
                FROM    STRING_SPLIT(STRING_AGG(t1.[Sample Values], '-'), '-')
            ) AS innerAgg(Result)
        ) as [Sample Values]
    from 
    (
        select
            'abc' as [Sample Values]
        union all
        select
            'def'
        union all
        select
            'ghi'
    ) t1
    

    它返回的结果为:

    abc" - "def" - "ghi
    

    我如何获得以下结果:

    "abc" - "def" - "ghi"
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   gotqn user3521065    3 年前

    只需将它们添加到外部选择中:

    select  '"' +
        (
            SELECT  STRING_AGG(TRIM(innerAgg.Result), '" - "')
            FROM
            (
                SELECT  DISTINCT
                    value
                FROM    STRING_SPLIT(STRING_AGG(t1.[Sample Values], '-'), '-')
            ) AS innerAgg(Result)
        )  + '"'  as [Sample Values]
    from 
    (
        select
            'abc' as [Sample Values]
        union all
        select
            'def'
        union all
        select
            'ghi'
    ) t1
    

    或者在预先形成的位置添加引号 DISTINCT :

    select  
        (
            SELECT  STRING_AGG(TRIM(innerAgg.Result), ' - ')
            FROM
            (
                SELECT  DISTINCT
                    CONCAT('"', value, '"')
                FROM    STRING_SPLIT(STRING_AGG(t1.[Sample Values], '-'), '-')
            ) AS innerAgg(Result)
        ) as [Sample Values]
    from 
    (
        select
            'abc' as [Sample Values]
        union all
        select
            'def'
        union all
        select
            'ghi'
    ) t1