SQL查询:在所有记录中查找唯一的数字组合

mkm*_*san 4 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
   4           10             22               50
   5           22             33               46           
Run Code Online (Sandbox Code Playgroud)

数字范围为1-60,并且组合中不重复相同的数字.订单无关紧要.

入口表

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
Run Code Online (Sandbox Code Playgroud)

数字范围为1-60,并且在条目中不重复相同的数字.订单无关紧要.

结果

  • 搜索组合1将不会产生任何结果
  • 搜索组合2将返回EntryID 2
  • 搜索组合3将不会产生任何结果
  • 搜索组合4将返回EntryID 1,6,7
  • 搜索组合5将返回EntryID 1,7

查询还应该在组合表中为每个记录显示它在Entry表中出现的次数.它应该排除Entry表中没有出现的组合.

小智 6

尝试:

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
Run Code Online (Sandbox Code Playgroud)

- 返回特定@CombID的匹配条目