2010-09-08 58 views
2

當一組給定說{1,2,3,4,5,6} 任務是separe對亞在TSQL(SQL 2005/2008)Set操作

{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})

回答

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 

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

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 
       );