0

我有一个包含两列标签和位置的表格。

Label                        Location
---------------------------------------
OLR-2873-SSA/GTA              GTA

OLR-2873-SSA/GTA              GTA

OLR-2873-SSA/POW              POW

OLR-2873-SSA/POWGTA           POWGTA

我希望输出像

Lable                                                     Location 
-----------------------------------------------------------------------
OLR-2873-SSA/GTA,OLR-2873-SSA/POW,OLR-2873-SSA/POWGTA      GTA,POW,POWGTA

我想使用正则表达式并让他输出。

我试过了

Select 
dbms_lob.substr( ltrim(REGEXP_REPLACE(REPLACE(
         REPLACE(
           XMLAGG(
             XMLELEMENT("A",label )
               ORDER BY label).getClobVal(),
             '<A>',','),
             '</A>',''),'([^,]+)(,\1)+', '\1'),
                  ','),4000,1) label , dbms_lob.substr( ltrim(REGEXP_REPLACE(REPLACE(
         REPLACE(
           XMLAGG(
             XMLELEMENT("A",location )
               ORDER BY location).getClobVal(),
             '<A>',','),
             '</A>',''),'([^,]+)(,\1)+', '\1'),
                  ','),4000,1) LOCATION from table_name. 

但我得到这样的输出

Label                                  Location
----------------
OLR-2873-SSA/GTA,OLR-2873-SSA/POWGTA   GTA,POWGTA
4

2 回答 2

0

微软 SQL 版本

DECLARE @Table AS TABLE (Label VARCHAR(25), Location VARCHAR(25))

INSERT INTO @Table (Label, Location) VALUES ('OLR-2873-SSA/GTA','GTA')
   ,('OLR-2873-SSA/GTA','GTA')
   ,('OLR-2873-SSA/POW','POW')
   ,('OLR-2873-SSA/POWGTA','POWGTA')

SELECT
    Label = STUFF(
        (SELECT ',' + Label
        FROM
            @Table t
        FOR XML PATH(''))
        ,1,1,'')
    ,Location = STUFF(
        (SELECT ',' + Location
        FROM
            @Table t
        FOR XML PATH(''))
        ,1,1,'')

基本上,您似乎正在寻找行中字符串的串联,如果您环顾互联网,有几种方法。我使用的一种方法是将行转换为 xml 字符串,其值前面有一个逗号,没有列名,然后使用东西来整理第一个逗号。所以FOR XML PATH('')基本上意味着没有根元素,然后因为没有列名,你也不会得到其他 xml 标签,例如 no <label></label>。将定界符添加到列的值中,您现在有一个长定界字符串,您只需要摆脱第一个不需要的定界符。

于 2016-06-14T16:48:53.523 回答
0

尝试这个

WITH TEST_DATA AS (
    SELECT 'OLR-2873-SSA/GTA' AS LABEL, 'GTA' AS LOCATION FROM DUAL
    UNION ALL
    SELECT 'OLR-2873-SSA/GTA' AS LABEL, 'GTA' AS LOCATION FROM DUAL
    UNION ALL
    SELECT 'OLR-2873-SSA/POW' AS LABEL, 'POW' AS LOCATION FROM DUAL
    UNION ALL
    SELECT 'OLR-2873-SSA/POWGTA' AS LABEL, 'POWGTA' AS LOCATION FROM DUAL
)
SELECT
    LISTAGG(CASE LABEL_DISTINCT WHEN 1 THEN LABEL END, ',') WITHIN GROUP(ORDER BY 0) AS LABEL,
    LISTAGG(CASE LOCATION_DISTINCT WHEN 1 THEN LOCATION END, ',') WITHIN GROUP(ORDER BY 0) AS LOCATION
FROM (
    SELECT
        LABEL,
        ROW_NUMBER() OVER(PARTITION BY LABEL ORDER BY 0) AS LABEL_DISTINCT,
        LOCATION,
        ROW_NUMBER() OVER(PARTITION BY LOCATION ORDER BY 0) AS LOCATION_DISTINCT
    FROM
        TEST_DATA
)
于 2016-06-15T04:33:59.543 回答