有人可以逐步解决这个问题吗?对称对问题

时间:2018-10-04 03:12:33

标签: sql-server

有人可以帮助初学者了解在MS SQL Server中解决此问题的过程。如果您有任何课程,您也会建议这样做。我拿了一些,但他们没有装备我解决这个问题。我是初学者。谢谢

enter image description here

2 个答案:

答案 0 :(得分:0)

基本上,您需要执行某种将数据连接到自身的操作(也称为自我连接),以便能够检查给定条件:

x1 = y2 and x2 = y1

我们可以使用以下查询来获取所有对:

DECLARE @DataSource TABLE
(
    [x] INT
   ,[y] INT
);

INSERT INTO @DataSource ([x], [y])
VALUES (20, 20)
      ,(20, 20)
      ,(20, 21)
      ,(23, 22)
      ,(22, 23)
      ,(21, 20);


WITH DataSource AS
(
    SELECT [x]
          ,[y]
          ,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS [RowID]
    FROM @DataSource
)
SELECT *
FROM DataSource DS1
INNER JOIN DataSource DS2
    ON DS1.[x] = DS2.[y]
    AND DS1.[y] = DS2.[x]
WHERE DS1.[RowID] <> DS2.[RowID];

enter image description here

我们使用ROW_NUMBER为每一行生成一个唯一的ID,以确保它不会与自身连接。

在示例结果中,只有该对的第一部分(其中x1 < x2,并且您获得唯一值。因此,我们可以对查询进行一些更改:

SELECT DISTINCT [x]
               ,[y]
FROM @DataSource DS1
WHERE EXISTS
(
    SELECT 1
    FROM @DataSource DS2
    WHERE DS1.[x] = DS2.[y]
        AND DS1.[y] = DS2.[x]
        AND DS1.[X] <= DS2.[x]
)
ORDER BY [x];

enter image description here

只有一个小小的变化。我们正在寻找该对中的一部分,其中x1<x2。当然,如果您更喜欢联接,则可以执行以下操作:

SELECT DISTINCT DS1.[x]
               ,DS1.[y]
FROM @DataSource DS1
INNER JOIN @DataSource DS2
    ON DS1.[x] = DS2.[y]
    AND DS1.[y] = DS2.[x]
    AND DS1.[x] <= DS2.[x]
ORDER BY DS1.[x];

答案 1 :(得分:0)

/* Case 1: Cases where x=y and have more than one record */
with tempa as
(
    select x,y
    from functions
    where x=y
    group by x,y
    having count(*)>=2
),
/* Case 2: Where x=y and y=x and x<>y */
tempb as
(
  select distinct A_X,A_Y from
    (
        select distinct a.x as A_X,a.y as A_Y, b.y as B_Y,b.x as B_X
        from functions a inner join functions b
        on a.x=b.y and a.y=b.x
    ) 
   where A_X<B_X
)
select * from 
(
    select * from tempa
    union 
    select * from tempb
)
 order by 1;