将列拆分为三列的新行

时间:2018-11-05 10:03:58

标签: sql sql-server database

我尝试使用; with tmp()并通过mssql合并所有但仍然没有运气。

这是我的消息来源

instance  |host   |servicename
DB,tomcat |abc,xyz|sap,java
null      |efg,ijn|D40,L90

我想得到这样的输出

instance|host|servicename
DB      |abc |sap
Tomcat  |xyz |java
        |efg |D40
        |ijn |L90

您有什么解决方案可以为此建立关系吗?

1 个答案:

答案 0 :(得分:1)

尝试一下

IF OBJECT_ID('tempdb..#Temp')IS NOT NULL
DROP TABLE #Temp
;WITH CTE(instance  ,host   ,servicename)
AS
(
SELECT 'DB,tomcat' ,'abc,xyz','sap,java' UNION ALL
SELECT null      ,'efg,ijn','D40,L90'
)

SELECT ROW_NUMBER()OVER(ORDER BY instance) AS Seq
        ,ISNULL(instance,'NA') AS instance
        ,Host
        ,servicename
 INTO #Temp FROM CTE

SELECT a.Seq
        ,Split.a.value('.','nvarchar(1000)') AS instance
        ,Split1.a.value('.','nvarchar(1000)') AS host
        ,Split2.a.value('.','nvarchar(1000)') AS servicename
FROM(
SELECT Seq
    ,CAST('<S>'+REPLACE(instance,',','</S><S>')+'</S>'  AS XML )AS instance
    ,CAST('<S>'+REPLACE(host,',','</S><S>')+'</S>'  AS XML )AS host
    ,CAST('<S>'+REPLACE(servicename,',','</S><S>')+'</S>'  AS XML )AS servicename
    FROM #Temp 
) As a
CROSS APPLY instance.nodes('S') AS Split(a)
CROSS APPLY host.nodes('S') AS Split1(a)
CROSS APPLY servicename.nodes('S') AS Split2(a)
ORDER BY seq