TSQL:查询以选择超集和子集对

时间:2016-06-24 13:46:02

标签: sql-server tsql

给出带有字段及其处理程序的表:

Field   Handler
----------------
"1"     "A"
"1"     "B"
"2"     "A"
"2"     "B"
"2"     "C"
"3"     "C"
"3"     "D"

每个字段可能有许多处理程序。我需要编写一个查询来选择具有超集和处理程序子集的字段。例如,因为字段“1”具有处理程序“A”和“B”,字段“2”具有处理程序的超集(“A”,“B”和“C”),所以我需要查询向我显示: / p>

SuperSet   SubSet
------------------
"2"        "1"
"3"        NULL

1 个答案:

答案 0 :(得分:1)

请不要告诉任何人我写这个代码,这非常hacky。

测试数据

CREATE TABLE #TestData (Field int, Handler varchar(10))
INSERT INTO #TestData (Field, Handler)
VALUES
 (1,'A')
,(1,'B')
,(2,'A')
,(2,'B')
,(2,'C')
,(3,'C')
,(3,'D')

查询

SELECT
a.Superset
,a.SubSet
FROM
(SELECT
a.Field SuperSet
,b.Field SubSet
FROM
(
SELECT
a.Field
,    STUFF((SELECT ', ' + b.Handler
           FROM #TestData b 
           WHERE b.Field = a.Field 
          FOR XML PATH('')), 1, 2, '') Result
FROM #TestData a
GROUP BY a.Field
) a
LEFT JOIN
(
SELECT
a.Field
,    STUFF((SELECT ', ' + b.Handler
           FROM #TestData b 
           WHERE b.Field = a.Field 
          FOR XML PATH('')), 1, 2, '') Result
FROM #TestData a
GROUP BY a.Field
) b
ON a.Result LIKE '%' + b.Result + '%'
AND b.Field <> a.Field
) a
LEFT JOIN
(
SELECT
a.Field SuperSet
,b.Field SubSet
FROM
(
SELECT
a.Field
,    STUFF((SELECT ', ' + b.Handler
           FROM #TestData b 
           WHERE b.Field = a.Field 
          FOR XML PATH('')), 1, 2, '') Result
FROM #TestData a
GROUP BY a.Field
) a
LEFT JOIN
(
SELECT
a.Field
,    STUFF((SELECT ', ' + b.Handler
           FROM #TestData b 
           WHERE b.Field = a.Field 
          FOR XML PATH('')), 1, 2, '') Result
FROM #TestData a
GROUP BY a.Field
) b
ON a.Result LIKE '%' + b.Result + '%'
AND b.Field <> a.Field
) b 
ON a.SuperSet = b.SubSet
WHERE b.SubSet IS NULL

结果

Superset    SubSet
2           1
3           NULL