SQL找到相同的组

Pat*_*ton 5 sql t-sql database sybase-ase

给出如下表:

id    key   val
----  ----  -----
bob   hair  red
bob   eyes  green
Run Code Online (Sandbox Code Playgroud)

还有另一张表:

id    key   val
----  ----  -----
fred  hair  red
fred  eyes  green
fred  shoe  42
joe   hair  red 
joe   eyes  green
greg  eyes  blue
greg  hair  brown
Run Code Online (Sandbox Code Playgroud)

我想在表b中找到与表中的人完全匹配的人,在这种情况下Bob和Joe.弗雷德不算数,因为他也有鞋码.这是在Sybase中,因此没有完全外连接.我想出了一个带有联盟的选择,这个联盟可以归还那些肯定不一样的人,但我不确定如何有效地选择那些人.

或者,如果它更简单,我如何检查b中的哪些组不止一次?

nik*_*trs 2

尝试这个

select a.id,b.id
from a 
join b on a.[key] = b.[key] and a.val = b.val -- match all rows
join (select id,count(*) total from a group by id) a2 on a.id = a2.id -- get the total keys for table a per id
join (select id,count(*) total from b group by id) b2 on b.id = b2.id -- get the total keys for table b per id
group by a.id,b.id,a2.total,b2.total
having count(*) = a2.total AND count(*) = b2.total -- the matching row's total should be equal with each tables keys per id
Run Code Online (Sandbox Code Playgroud)

在 @t-clausen.dk 评论之后,我对原始 sql 代码进行了修改。在这种情况下,我计算两个表上匹配的每个不同的对/值,每个表都不同的对/值。

select td.aid,td.bid
from (
select a.id as aid,b.id as bid, count(distinct a.[key]+' '+a.val) total
from a 
join b on a.[kry] = b.[key] and a.val = b.val
group by a.id,b.id
) td -- match all distinct attribute rows
join (select id,count(distinct [key]+' '+val) total from a group by id) a2 on td.aid = a2.id -- get the total distinct keys for table a per id
join (select id,count(distinct [key]+' '+val) total from b group by id) b2 on td.bid = b2.id -- get the total keys for table b per id
where td.total = a2.total AND td.total = b2.total -- the matching distinct attribute total should be equal with each tables distinct key-val pair

Tested on

Table a

bob     hair    red
bob     eyes    green
nick    hair    red
nick    eyes    green
nick    shoe    45

Table b

fred    hair    red
fred    eyes    green
joe     hair    red
joe     eyes    green
fred    shoe    42
Run Code Online (Sandbox Code Playgroud)