why*_*heq 4 sql t-sql sql-server sql-server-2008 sql-server-2008-r2
在轻微的心理纠结中,我希望这比我想象的容易.得到以下表格:
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
Run Code Online (Sandbox Code Playgroud)
这将返回以下内容:

我只希望此查询在a的所有三个cardid存在时返回行handid.因此,期望的结果集将不包括handid3.
这是现实的典范.实际上,#x包含500个记录.
编辑
好的 - 实际上有一些获胜者由数据集组成,#winners其中包含可变数量的记录.因此,将原始代码修改为以下结果集不应包含handId1或handId3.我还在结果集中获得了一些不需要的重复记录:
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
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的东西:
select handid
from #x
where cardid in (select cardid from #winners)
group by handid
having count(handid) = (select count(distinct cardid)
from #winners);
Run Code Online (Sandbox Code Playgroud)
结果:
| HANDID |
----------
| 2 |
| 4 |
Run Code Online (Sandbox Code Playgroud)
根据您的编辑,这是一个返回正确结果的尝试,但我不确定它是否适用于您拥有的较大数据集:
;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
Run Code Online (Sandbox Code Playgroud)
结果:
| HANDID |
----------
| 2 |
| 4 |
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |