Sql Server:逗号分隔的列值存在于其他逗号分隔列中

时间:2016-09-26 11:01:18

标签: sql sql-server

我们说我有一张桌子

OrgData
OrgDataid  columvalues
1          1,2,3,4,5
2          6,7,8,9
3          16,17,18,19

另一个表包含选定的值

selectedData
rowid   sid   orgid   values
1       1     1       1,2
2       1     2       6,7,8,9
3       2     1       1,2,3,4,5

其中sid是OrgData的id

我想输出

表示sid 1;

outputData
OrgData   columvalues
1         partial selected
2         Full selected
3         Nothing selected

我想要一些直接的查询,而我正在尝试将每个逗号分隔成行并为每个逗号循环。

谢谢

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

带有数据的

- 模拟表

require

- 首先拆分OrgData的CTE

DECLARE @OrgData TABLE(OrgDataid INT,columvalues VARCHAR(100));
INSERT INTO @OrgData VALUES
 (1,'1,2,3,4,5')
,(2,'6,7,8,9')
,(3,'16,17,18,19');

DECLARE @selectedData TABLE(rowid INT,[sid] INT,orgid INT,[values] VARCHAR(100));
INSERT INTO @selectedData VALUES
 (1,1,1,'1,2')
,(2,1,2,'6,7,8,9')
,(3,2,1,'1,2,3,4,5');

- 分割SelectedData的第二个CTE

WITH OrgDataSplitted AS
(
    SELECT od.*
          ,LEN(od.columvalues)-LEN(REPLACE(od.columvalues,',',''))+1 AS CountParts
          ,B.Part.value('.','int') AS PartInt
    FROM @OrgData AS od
    CROSS APPLY(SELECT CAST('<x>' + REPLACE(columvalues,',','</x><x>') + '</x>' AS XML)) AS A(Casted)
    CROSS APPLY A.Casted.nodes('/x') AS B(Part)
)

- 加入他们的查询

,SelectedSplitted AS
(
    SELECT sd.*
          ,B.Part.value('.','int') AS PartInt
    FROM @selectedData AS sd
    CROSS APPLY(SELECT CAST('<x>' + REPLACE([values],',','</x><x>') + '</x>' AS XML)) AS A(Casted)
    CROSS APPLY A.Casted.nodes('/x') AS B(Part)
)

结果。如果CountParts和CountIdent是相同它已满,&gt; 0是部分而0是 none

SELECT o.OrgDataid,o.CountParts,s.rowid,COUNT(rowid) AS CountIdent
FROM Orgdatasplitted AS o
FULL OUTER JOIN SelectedSplitted AS s ON o.OrgDataID=s.orgid and o.PartInt=s.PartInt
GROUP BY o.OrgDataid,o.CountParts,s.rowid
ORDER BY o.OrgDataid

答案 1 :(得分:0)

尝试以下脚本,可能会对您有所帮助。但我同意@Gordon Linoff, 修复数据结构。以逗号分隔的字符串存储值是错误的方法。

SELECT  OrgDataid
        ,(CASE  WHEN OD.columvalues = SD.[values] THEN 'Full selected'
                WHEN SD.rowid IS NULL THEN 'Nothing selected'
         ELSE 'partial selected' END) AS columvalues
FROM    OrgData AS  OD
LEFT OUTER JOIN selectedData AS SD ON OD.columvalues LIKE '%'+SD.[values]+'%'