我有一个带有两列标签和位置的表。
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
答案 0 :(得分:0)
Microsoft 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字符串,其中包含前缀值且没有列名称的逗号,然后使用stuff来整理第一个逗号。所以FOR XML PATH('')
基本上没有根元素,因为没有列名,你就不会得到其他的xml标签,例如没有<label></label>
。将分隔符添加到列的值中,您现在可以使用长分隔字符串来删除第一个不需要的分隔符。
答案 1 :(得分: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
)