从我的sql

时间:2017-06-23 06:24:12

标签: sql sql-server tsql

我的输入代码就像,

Emp_ID       Scenarios
10902543     SCENARIO 3, SCENARIO 1, SCENARIO 1, SCENARIO 4
11083080     SCENARIO 3, SCENARIO 1, SCENARIO 3
10988779     SCENARIO 4, SCENARIO 1, SCENARIO 4, SCENARIO 3

并希望输出应该是,

Emp_ID       Scenarios
10902543    SCENARIO 3, SCENARIO 1, SCENARIO 4
11083080    SCENARIO 1, SCENARIO 3
10988779    SCENARIO 1, SCENARIO 4, SCENARIO 3

需要在没有while循环的情况下执行此操作,请您建议任何其他选择。

2 个答案:

答案 0 :(得分:2)

首先使用SplitString函数,然后使用Distinct方案值,最后使用For xml path + STUFF

加入
DECLARE @SampleData AS TABLE
(
 Emp_ID int,
 Scenarios varchar(200)   
)

INSERT INTO @SampleData
(
    Emp_ID,
    Scenarios
)
VALUES
( 10902543, 'SCENARIO 3, SCENARIO 1, SCENARIO 1, SCENARIO 4'),
( 11083080, 'SCENARIO 3, SCENARIO 1, SCENARIO 3'),
( 10988779, 'SCENARIO 4, SCENARIO 1, SCENARIO 4, SCENARIO 3')

SELECT sd.Emp_ID, s.Scenarios
FROM @SampleData sd
CROSS APPLY
(
    SELECT STUFF((  
                SELECT DISTINCT ', '+ s.Value
                FROM [dbo].[SplitString](sd.Scenarios, ',') s
                FOR XML PATH('')
             )
    , 1,2,'') AS Scenarios

) s

分割功能

CREATE FUNCTION [dbo].[SplitString] (@Text varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
   Select Pos = Row_Number() over (Order By (Select null))
        ,Value = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
   From (Select x = Cast('<x>'+ Replace(@Text,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
   Cross Apply x.nodes('x') AS B(i)
);

返回

Emp_ID      Scenarios
-----------------------------------------------
10902543    SCENARIO 1, SCENARIO 3, SCENARIO 4
11083080    SCENARIO 1, SCENARIO 3
10988779    SCENARIO 1, SCENARIO 3, SCENARIO 4

答案 1 :(得分:1)

使用XML方法的另一种方法

<强>架构:

CREATE TABLE #TAB(Emp_ID BIGINT, Scenarios VARCHAR(MAX))

INSERT INTO #TAB

SELECT 10902543,'SCENARIO 3, SCENARIO 1, SCENARIO 1, SCENARIO 4'
UNION ALL
SELECT 11083080,'SCENARIO 3, SCENARIO 1, SCENARIO 3'
UNION ALL
SELECT 10988779,'SCENARIO 4, SCENARIO 1, SCENARIO 4, SCENARIO 3'

现在拆分方案,应用Distinct&amp;用逗号添加它们。

;WITH CTE AS(
    SELECT DISTINCT Emp_ID,  SPLT.B.value('.','varchar(max)') Scenarios 
    FROM(
        SELECT Emp_ID, Scenarios
        ,CAST( '<M>'+REPLACE(Scenarios,', ','</M><M>')+'</M>' AS XML) XML_DATA
        FROM #TAB
    )A
    CROSS APPLY
    A.XML_DATA.nodes('/M') AS SPLT(B)
)
SELECT DISTINCT Emp_ID
, STUFF((SELECT ','+Scenarios
FROM CTE C1 
WHERE C1.Emp_ID = C2.Emp_ID FOR XML PATH(''),TYPE
).value('.','varchar(max)'),1,1,'') as Scenarios FROM CTE C2

<强>结果:

+----------+----------------------------------+
|  Emp_ID  |            Scenarios             |
+----------+----------------------------------+
| 10902543 | SCENARIO 1,SCENARIO 3,SCENARIO 4 |
| 10988779 | SCENARIO 1,SCENARIO 3,SCENARIO 4 |
| 11083080 | SCENARIO 1,SCENARIO 3            |
+----------+----------------------------------+