SQLite查询以确定前6个中奖乐透号码

时间:2019-10-24 08:48:41

标签: sqlite

所以数据库是这个:

CREATE TABLE Combination
(combinationNo INTEGER PRIMARY KEY NOT NULL,
N1 INTEGER NOT NULL,
N2 INTEGER NOT NULL,
N3 INTEGER NOT NULL,
N4 INTEGER NOT NULL,
N5 INTEGER NOT NULL,
N6 INTEGER NOT NULL,
UNIQUE (N1, N2, N3, N4, N5, N6)
);
CREATE TABLE Draw
(drawNo INTEGER PRIMARY KEY NOT NULL,
drawDate DATE NOT NULL,
drawName TEXT,
winCombinationNo INTEGER,
FOREIGN KEY (winCombinationNo) REFERENCES Combination (combinationNo)
);
CREATE TABLE Ticket
(ticketNo INTEGER PRIMARY KEY NOT NULL,
drawNo INTEGER NOT NULL,
soldAt TEXT NOT NULL,
FOREIGN KEY (drawNo) REFERENCES Draw (drawNo)
);
CREATE TABLE Line
(ticketNo INTEGER NOT NULL,
lineID TEXT NOT NULL,
combinationNo INTEGER NOT NULL,
PRIMARY KEY (ticketNo, lineID),
FOREIGN KEY (ticketNo) REFERENCES Ticket (ticketNo),
FOREIGN KEY (combinationNo) REFERENCES Combination (combinationNo)
);

我看到了

FOREIGN KEY (winCombinationNo) REFERENCES Combination (combinationNo)

但到目前为止,我只有这样:

SELECT combinationNo
FROM Combination
WHERE
LIMIT 6;

我知道我需要在某个地方使用联接,但我不知道要使用哪个联接,在哪里或如何使用。

1 个答案:

答案 0 :(得分:0)

我相信您可以做类似的事情:-

WITH 
    drawNumber AS (SELECT 2 /*<<<<<<<<<< The drawNo  */),
    winningNumbers(wn) AS 
        (
            SELECT n1||','||n2||','||n3||','||n4||','||n5||','||n6 FROM Draw JOIN Combination ON Draw.winCombinationNo = Combination.combinationNo WHERE Draw.drawNo = (SELECT * FROM drawNumber)
        )
SELECT 
    Ticket.ticketNo AS TicketNo, 
    Line.LineId, 
    n1||' '||n2||' '||n3||' '||n4||' '||n5||' '||n6 AS Entry,
    (SELECT * FROM winningNumbers) AS WinningNumbers,
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n1||',') > 0) +
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n2||',') > 0) +
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n3||',') > 0) +
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n4||',') > 0) +
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n5||',') > 0) +
    (instr((SELECT ','||wn||',' FROM winningNumbers),','||n6||',') > 0)
    AS score
FROM Line 
    JOIN Combination ON Line.CombinationNo = Combination.combinationNo
    JOIN Ticket ON Ticket.ticketNo = Line.TicketNo
WHERE score > 0 AND DrawNo = (SELECT * FROM drawNumber)
ORDER BY score DESC 
LIMIT 6
;

这将产生类似:-

的结果

enter image description here

  • 请注意,由于缺乏信息,获胜的决定可能与预期的有所不同。

以上是基于随机生成多达100000个组合(通过除去相同数字的组合而减少)和每行包含4个抽奖的单行生成20000张彩票的情况(drawNo为1-4)。

如果要考虑线分数的累积,那将仅仅是按分数分组并获取分数总和的问题。