SQL查询:在所有记录中查找唯一的数字组合
我正在尝试在SQL Server中创建一个查询,该查询将搜索表中的所有数字组合 组合表SQL查询:在所有记录中查找唯一的数字组合,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我正在尝试在SQL Server中创建一个查询,该查询将搜索表中的所有数字组合 组合表 CombID Comb_Num1 Comb_NumTwo Comb_NumThree 1 1 2 3 2 2 10 15 3 5 20 60
CombID Comb_Num1 Comb_NumTwo Comb_NumThree
1 1 2 3
2 2 10 15
3 5 20 60
4 10 22 50
5 22 33 46
EntryID NumberOne NumberTwo NumberThree NumberFour NumberFive
1 10 22 33 46 50
2 2 10 15 22 40
3 24 33 40 45 50
4 5 10 22 40 60
5 2 6 10 22 40
6 2 10 22 50 60
7 10 22 33 46 50
数字范围为1-60,相同的数字不会在组合中重复。秩序并不重要
条目表
CombID Comb_Num1 Comb_NumTwo Comb_NumThree
1 1 2 3
2 2 10 15
3 5 20 60
4 10 22 50
5 22 33 46
EntryID NumberOne NumberTwo NumberThree NumberFour NumberFive
1 10 22 33 46 50
2 2 10 15 22 40
3 24 33 40 45 50
4 5 10 22 40 60
5 2 6 10 22 40
6 2 10 22 50 60
7 10 22 33 46 50
数字范围为1-60,同一个数字在条目中不会重复。秩序并不重要
结果
- 搜索组合1不会产生任何结果
- 搜索组合2将返回EntryID 2
- 搜索组合3不会产生任何结果
- 搜索组合4将返回EntryID 1、6、7
- 搜索组合5将返回EntryID 1,7
select distinct e.EntryID
from entry e, combination c
where c.Comb_Num1 in (e.NumberOne, e.NumberTwo, e.NumberThree, e.NumberFour, e.NumberFive)
and c.Comb_Num2 in (e.NumberOne, e.NumberTwo, e.NumberThree, e.NumberFour, e.NumberFive)
and c.Comb_Num3 in (e.NumberOne, e.NumberTwo, e.NumberThree, e.NumberFour, e.NumberFive)
and c.CombID = @CombID
-要返回特定@CombID的匹配项,暴力将执行以下操作:
SELECT EntryID
FROM combinations
INNER JOIN entries ON
(Comb_Num1=NumberOne AND Comb_NumTwo=NumberTwo AND Comb_NumThree=NumberThree)
OR (Comb_Num1=NumberTwo AND Comb_NumTwo=NumberThree AND Comb_NumThree=NumberFour)
OR (Comb_Num1=NumberThree AND Comb_NumTwo=NumberFour AND Comb_NumThree=NumberFive)
WHERE CombID=<whatever>
选择EntryID
来自组合
上的内部联接项
(Comb_numm1=NumberOne,Comb_NumTwo=NumberTwo,Comb_NumThree=numbertree)
或者(Comb_Num1=NumberTwo,Comb_NumTwo=numbertree,Comb_numtree=NumberFour)
或者(Comb_Num1=numbertree,Comb_NumTwo=NumberFour,Comb_NumThree=NumberFive)
康比德在哪里=
当然,这会考虑到你不想要的顺序。要解决此问题,您可以创建另一个表(一次创建),该表对Comb_Num1、CombNumTwo和CombNumThree的所有排列具有相同的CombID),或者以相同的方式扩展疯狂连接条件。这留给读者作为练习。到目前为止,您尝试了什么SQL?目前,这看起来像是一个考试题。在发布之前,我尝试过暴力法,但是所需的组合数量会使其难以适应,特别是当组合越来越大,条目数量越来越多时。我曾尝试将其分解为5个单独的SQL子查询,但在加入它们时,似乎又回到了蛮力式的方法。我不会拒绝投票,因为这在技术上是可行的,但这比Mark的答案复杂得多。