在TSQL上设置操作(SQL 2005/2008)

时间:2010-09-08 06:47:05

标签: tsql join

当给出一组时说{1,2,3,4,5,6} 任务是分配一对子集

{1,2},
{1,3},
{1,4},
{1,5},
{1,6},
{2,3},
{2,4},
{2,5},
{2,6},
{3,4},
{3,5},
{3,6},
{4,5},
{5,6}

所以当我有一张桌子时

Table Element
1
2
3
4
5
6

列出所有可能的逗号分隔子集的方法是什么? (可以忽略重复项(即){1,2}与{2,1}相同

2 个答案:

答案 0 :(得分:4)

SELECT T1.elem, T2.elem
FROM MyTable T1
INNER JOIN MyTable T2
ON T2.elem > T1.elem

...让你大部分时间都在这里 - 如果你想把它们显示为套装那么......

SELECT '{' + CAST(T1.elem AS VARCHAR(12)) + ', ' + CAST(T2.elem AS VARCHAR(12)) + '}'
FROM MyTable T1
INNER JOIN MyTable T2
ON T2.elem > T1.elem

......就是你所追求的。

答案 1 :(得分:0)

以下是使用CTE解决问题的方法。它不是特别优雅,但它完成了工作。

DECLARE @set TABLE (Element INT);

INSERT INTO @set(Element) VALUES (1);
INSERT INTO @set(Element) VALUES (2);
INSERT INTO @set(Element) VALUES (3);
INSERT INTO @set(Element) VALUES (4);
INSERT INTO @set(Element) VALUES (5);
INSERT INTO @set(Element) VALUES (6);

;WITH array (Element1, Element2, Row)
AS
(
SELECT t.Element
     , t2.Element
     , ROW_NUMBER() OVER(ORDER BY t.Element)
  FROM @set AS t
 CROSS JOIN @set AS t2
 WHERE t.Element <> t2.Element  
)
SELECT a.Element1
     , a.Element2
     , '{' + CONVERT(VARCHAR(5),a.Element1) + ',' + CONVERT(VARCHAR(5),a.Element2) + '}' AS 'Subset'
  FROM array AS a
 WHERE NOT EXISTS (SELECT *
                     FROM array AS sa
                    WHERE sa.Element1 = a.Element2 
                      AND sa.Element2 = a.Element1 
                      AND sa.Row < a.Row 
                  );