如何检索以逗号分隔的单列,并在sql中应用联接

4xrmg8kj  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(340)

我在sql中有以下两个表。我想从CalendarSchedule获取calendarid,并与calendar表联接以获取每个productid的calendarcode。输出格式如下所述。ms sql server 2012版本字符串\u拆分不起作用。请帮助获得所需的输出。
表1:压延时间表

productid, calendarid
100        1,2,3
200        1,2

表2:日历

calendarid, calendarCode
1           SIB 
2           SIN 
3           SIS

输出:

productId, calendarCode
100        SIB,SIN,SIS
200        SIB,SIN
tjrkku2a

tjrkku2a1#

您可以通过将数据转换为xml,然后使用cross-apply将其拆分来规范化数据。标准化后,使用stuff函数将日历代码组合成逗号分隔的列表。试试这个:

;WITH normalized_data as (
SELECT to_xml.productid
 ,split.split_calendarid 
FROM
     (
     SELECT *,
        cast('<X>'+replace(cs.calendarid,',','</X><X>')+'</X>' as XML) as xmlfilter
     FROM calendarschedule cs
     ) to_xml
 CROSS APPLY
     ( 
     SELECT new.D.value('.','varchar(50)') as split_calendarid 
     FROM to_xml.xmlfilter.nodes('X') as new(D)
     ) split
)   select distinct
        n.productid
        ,STUFF(
             (SELECT distinct ', ' + c.calendarCode
              FROM calendar c
              JOIN normalized_data n2 on n2.split_calendarid = c.calendarid
              WHERE n2.productid = n.productid
              FOR XML PATH ('')), 1, 1, '') calendarCode
    from normalized_data n

我觉得这个解决方案有点过于复杂了,但这是我让它工作的唯一方法。如果有人知道如何简化它,我很乐意听到一些反馈。

相关问题