有点精神上的纠结,我希望这比我想象的要容易。
得到以下表格:
create table #x
(
handid int,
cardid int
)
insert into #x
values
(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),
(2,2),(2,3),(2,4),(2,300),(2,400),(2,500),(2,8),
(3,2),(3,3),(3,4),(3,300),(3,400),(3,7),(3,8),
(4,2),(4,300),(4,400),(4,500),(4,6),(4,7),(4,8)
create table #winners(cardid int)
insert into #winners values(300),(400),(500)
select a.*
from
#x a
inner join #winners b
on
a.cardid = b.cardid
这将返回以下内容:
当
cardid
的所有三个 handid
都存在时,我只希望此查询返回行。因此所需的结果集将不包括 handid
3。这是一个现实模型。
实际上#x 包含 500 条轧机记录。
编辑
好的 - 实际上有赢家是由来自
#winners
的数据集组成的,这些数据集具有可变数量的记录。因此,将原始代码修改为以下结果集不应包含 handId
1 或 handId
3。我还在结果集中获得了一些不需要的重复记录:create table #x
(
handid int,
cardid int
)
insert into #x
values
(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8000),
(2,2),(2,3),(2,4),(2,300),(2,400),(2,500),(2,8),
(3,2),(3,3),(3,4),(3,300),(3,400),(3,7),(3,8),
(4,2),(4,300),(4,400),(4,500),(4,6),(4,7),(4,8)
create table #winners(winningComb char(1), cardid int)
insert into #winners values('A',300),('A',400),('A',500),('B',8000),('B',400)
select a.*
from
#x a
inner join #winners b
on
a.cardid = b.cardid
最佳答案
你可以使用这样的东西:
select handid
from #x
where cardid in (select cardid from #winners)
group by handid
having count(handid) = (select count(distinct cardid)
from #winners);
见 SQL Fiddle with Demo
结果:
| HANDID |
----------
| 2 |
| 4 |
根据您的编辑,这里尝试返回正确的结果,但我不确定它是否适用于您拥有的更大的数据集:
;with cte as
(
select w1.cardid, w1.winningComb, w2.ComboCardCount
from winners w1
inner join
(
select COUNT(*) ComboCardCount, winningComb
from winners
group by winningComb
) w2
on w1.winningComb = w2.winningComb
)
select a.handid
from x a
inner join cte b
on a.cardid = b.cardid
where a.cardid in (select cardid from cte)
group by handid, b.ComboCardCount
having COUNT(a.handid) = b.ComboCardCount
见 SQL Fiddle with Demo
结果:
| HANDID |
----------
| 2 |
| 4 |