Oracle:多个逗号分隔的变量ID到变量名称

时间:2016-08-27 14:35:29

标签: sql oracle

表格包含以下列:

表1:

    Client_Name                   | VAR_ID  
Row 1: SchwabM5-Prodtest-Strategy | 3025,2937    
Row 2: SchwabM5-Prodtest-Strategy | 5,7     

表2:

   Client_Name                    | VAR_ID   
Row 1: A                          | 3025  
Row 2: B                          | 5   
Row 1: C                          | 2937   
Row 2: D                          | 7   

问题:我希望单个查询中的输出如下表所示?

Client_Name                       | VAR_ID   
Row 1: SchwabM5-Prodtest-Strategy | A,C       
Row 2: SchwabM5-Prodtest-Strategy | B,D

你能帮我解决一下我可以获得上述输出的问题吗?

1 个答案:

答案 0 :(得分:-1)

CREATE TABLE [dbo].[Table1](
    [name] [nvarchar](50) NULL,
    [var_id] [nvarchar](50) NULL
) 

表1中的数据

SchwabM5-Prodtest-Strategy | 3025,2937    
SchwabM5-Prodtest-Strategy | 5,7 

表2

CREATE TABLE [dbo].[Table2](
    [name] [nvarchar](50) NULL,
    [var_id] [int] NULL
)

表2中的数据

A                          | 3025  
B                          | 5   
C                          | 2937   
D                          | 7  

运行以下查询

WITH [RESULTS]
AS
(
    SELECT  
        [NAME]
       ,CAST ('<Nodes><Node>' + replace([var_id],',','</Node><Node>') + '</Node></Nodes>' AS XML) NODEXML
    FROM [dbo].Table1
)
SELECT [NAME] ,
        STUFF((SELECT ',' + [name] FROM [dbo].Table2 WHERE var_id IN 
                ( 
                    SELECT  tab.col.value('.','int') FROM NODEXML.nodes('//Node') AS tab(col)
                ) FOR XML PATH('')),1,1,'') CONTENT
FROM RESULTS