获取一行分组对象

时间:2017-10-10 10:35:28

标签: sql sql-server

我有一张桌子,其中包含一位丈夫对妻子的真实情况。 该表包含每行两个行(BTW,性别没有意义。可能是丈夫 - 丈夫和妻子 - 妻子。只是说)。意思是,该表可能显示"连接"的两行结果: Wife--Husband和\或Husband--Wife 该表如下所示:

 Id1    | Id2  | ConnectiondID  |  RelatedConnectionId
 -----------------------------------------------------
 123    | 333  |    FF45        |        F421
 333    | 123  |    F421        |        FF45
 456    | 987  |    F333        |        F321
 987    | 456  |    F321        |        F333

我的预期结果是每组只有一个关系:

Id1  | Id2
----------
123  | 333
456  | 987

3 个答案:

答案 0 :(得分:1)

这实际上非常简单,假设您只想要情侣,并且您的ID值都是唯一且数字的,并且不需要任何自联接,功能或分组:

declare @t table(Id1 int,Id2 int,ConnectiondID nvarchar(5),RelatedConnectionId nvarchar(5));
insert into @t values(123,333,'FF45','F421'),(333,123,'F421','FF45'),(456,444,'FF46','F422'),(444,456,'F422','FF46'),(789,555,'FF47','F423'),(555,789,'F423','FF47');

select *
from @t
where Id1 < Id2
order by Id1

输出:

+-----+-----+---------------+---------------------+
| Id1 | Id2 | ConnectiondID | RelatedConnectionId |
+-----+-----+---------------+---------------------+
| 123 | 333 | FF45          | F421                |
| 444 | 456 | F422          | FF46                |
| 555 | 789 | F423          | FF47                |
+-----+-----+---------------+---------------------+

答案 1 :(得分:0)

如果我正确理解您的问题,您需要在桌面上执行自我加入,例如ON t1.id1 = t2.id2ON t1.ConnectionId = t2.RelatedConnectionID,显然这是两种方式。

要将此限制为仅一种方式,请在连接谓词上添加条件,使其中一个值小于或大于另一个值; e.g。

DECLARE @tbl table( Id1 smallint PRIMARY KEY, Id2 smallint,ConnectiondID char(5),RelatedConnectionId char(5));
INSERT @tbl(Id1,Id2,ConnectiondID,RelatedConnectionId)
 VALUES(123,333,'FF45','F421'),
       (333,123,'F421','FF45'),
       (456,222,'FF45','F421'),
       (222,456,'F421','FF45'),
       (789,111,'FF45','F421'),
       (111,789,'F421','FF45');

SELECT * 
FROM @tbl t1
JOIN @tbl t2 ON t2.Id1 = t1.Id2 AND t2.Id1 > t1.Id1;

答案 2 :(得分:0)

例如

DECLARE @T TABLE (id1 int, id2 int,ConnectiondID varchar(5),RelatedConnectionId varchar(5) )
 INSERT INTO @T (Id1,Id2,ConnectiondID,RelatedConnectionId)
 VALUES
 (123    , 333 ,'FF45','F421'),
 (333    , 123 , 'F421','FF45'),
 (2123    , 2333 ,'2FF45','2F421'),
 (2333    , 2123 , '2F421','2FF45'),
 (3    , 2 , 'AAAA','BBB'),
 (2    , 3 , 'BBB','AAAA')

SELECT  
    a.*
FROM 
    @t a
WHERE 
    CASE 
    WHEN ConnectiondID > RelatedConnectionId
    THEN RelatedConnectionId
    ELSE NULL 
    END IS NULL