簡體   English   中英

SQL查詢:在所有記錄中查找唯一的數字組合

[英]SQL query: Finding unique number combinations within all records

我試圖在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           

數字范圍為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

數字范圍為1-60,並且在條目中不重復相同的數字。 訂單無關緊要。

結果

  • 搜索組合1將不會產生任何結果
  • 搜索組合2將返回EntryID 2
  • 搜索組合3將不會產生任何結果
  • 搜索組合4將返回EntryID 1,6,7
  • 搜索組合5將返回EntryID 1,7

查詢還應該在組合表中為每個記錄顯示它在Entry表中出現的次數。 它應該排除Entry表中沒有出現的組合。

嘗試:

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>

這種做法是考慮到你不想要的訂單。 要解決此問題,您要創建另一個表(一次創建),對於Comb_Num1,CombNumTwo和CombNumThree的所有排列具有相同的CombID,或者以相同的方式擴展瘋狂連接條件。 這是作為練習留給讀者的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM