Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck for winning tickets in lottery using SQL
    primarykey
    data
    text
    <p>I have a SQL efficiency question. This is concerning the Norwegian national lottery. They draw seven numbers and three bonus balls. </p> <p>I have a database with all the drawings and a lot of tickets. The question is what is the most efficient table structure and way of getting all the winning tickets in a draw.</p> <p>These are my two main tables:</p> <pre><code>LotteryDraw DrawId (int, PK) DrawDate (datetime) MainNumbers (varchar) BonusNumbers (varchar) Main1 (smallint) Main2 (smallint) Main3 (smallint) Main4 (smallint) Main5 (smallint) Main6 (smallint) Main7 (smallint) Bonus1 (smallint) Bonus2 (smallint) Bonus3 (smallint) </code></pre> <p>I store each of the main- and bonus numbers both separately as well as a comma separated string in sorted order. </p> <p>Similary I've got:</p> <pre><code>LotteryTicket TicketId (int, PK) UserId (int, FK) ValidTill (datetime) MainNumbers (varchar) Main1 (smallint) Main2 (smallint) Main3 (smallint) Main4 (smallint) Main5 (smallint) Main6 (smallint) Main7 (smallint) </code></pre> <p>You get prizes for 4+1, 5, 6, 6+1 and 7 correct numbers (correct main numbers + bonus numbers). Anyone have any great ideas on how to write efficient SQL that will return all LotteryTickets with a prize for a give draw date? ValidTill is the last draw date where a ticket was valid.</p> <p>My current attempt is using Linq2Sql in C# and has the speed of a hippo on ice so I really need some SQL expertise.</p> <p>Server is Microsoft SQL Server 2008 R2 if that matters.</p> <p>Update: After tweaking the answer from Mark B. I ended up with the following query. I needed to normalize the database a bit by adding a new table LotteryTicketNumber (ticketid, number). </p> <pre><code>SELECT LotteryTicket.TicketID, count(LotteryTicket.Numbers) AS MainBalls, ( SELECT top 1 ltn.Number FROM LotteryTicketNumber ltn WHERE ltn.Number IN (2,4,6) AND ltn.TicketId = LotteryTicket.TicketId ) As BonusBall FROM LotteryTicket LEFT JOIN LotteryTicketNumber ON LotteryTicket.TicketId = LotteryTicketNumber.TicketId WHERE LotteryTicketNumber.Number IN (13,14,16,23,26,27,30) GROUP BY LotteryTicket.TicketID HAVING count(LotteryTicketNumber.Number) &gt;= 4 </code></pre> <p>The above query returns all tickets with at least 4 correct main numbers. Also the field Bonusball != NULL if the same ticket has one or more bonus balls. This is sufficient for me.</p> <p>Thanks for the help</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload