问题
i have this structure - its series of games registered each game has min 2 players, but can have up to many people playing in the same game :
gamenumber,team,name,points
1000,team tower, Tom Smith, 100
1000,team vegas, John Little, 90
1000,team windy, Andy Cooper, 20
1001,team woods, Marie Jones, 120
1001,team windy, Andy Cooper, 40
1002,team woods, Marie Jones, 20
1002,team tower, Tom Smith, 11
1003,team tower, Tom Smith, 89
1003,team bars, Jonathan Swift, 21
1003,team hammock, Bill Mccain, 31
1003,team windy, Andy Cooper, -1
To extract all 'Tom Smith's' games i execute this query - which is working fine :
select id, gamenumber, team, name, points
from `games`
where gamenumber in (
select gamenumber
from `games`
where name = 'Tom Smith'
and team = 'team tower'
)
It extracts all the games tom' has played, and all the gameid's for the game that tom played so it generates a list of the full game.
What i would like is to be able to ex filter and say :
1) i want all games ( full game, meaning similar as above where it extracts all the gameid records on the game), where Tom Smith has played Andy Cooper - and only the games where he played Andy Cooper.
It should include games where Tom and Andy maybe played more than only the 2, but only games where these 2 has been playing together with each other.
the above data set the result im after would be :
gamenumber,team,name,points
1000,team tower, Tom Smith, 100
1000,team vegas, John Little, 90
1000,team windy, Andy Cooper, 20
1003,team tower, Tom Smith, 89
1003,team bars, Jonathan Swift, 21
1003,team hammock, Bill Mccain, 31
1003,team windy, Andy Cooper, -1
1004,team woods, Andy Cooper, 70
1004,team tower, Tom Smith, 53
is it possible in a sqlite query to do that >
2) If im able to get the above list of games where the 2 played each other, i would also like to be able to do: 2.1) which games did Tom win against Andy ? ( Tom had the highest score within a gameid )
Result wished from dataset :
1000,team tower, Tom Smith, 100
1000,team vegas, John Little, 90
1000,team windy, Andy Cooper, 20
1003,team tower, Tom Smith, 89
1003,team bars, Jonathan Swift, 21
1003,team hammock, Bill Mccain, 31
1003,team windy, Andy Cooper, -1
2.2) Summary of amount ofgames where Tom won the whole game, and Andy was playing in too - and summary of Tom's point in games where he plays Andy and was winner of game (position 1) - result wished from dataset :
2, 189
Would like it to be 3 seperate queries as i want to use them for different purpose - if its possible to do this in queries ?
回答1:
One simple approach is aggregation:
SELECT id, gamenumber, team, name, points
FROM games
WHERE gamenumber IN (
SELECT gamenumber
FROM games
WHERE
(name = 'Tom Smith' AND team = 'team tower') OR
(name = 'Andy Cooper' AND team = 'team windy')
GROUP BY gamenumber
HAVING MIN(name) <> MAX(name)
);
Demo
来源:https://stackoverflow.com/questions/57949537/sqlite-extract-sets-of-data-where-different-rows-within-a-set-needs-to-have-a-ce