我有一个带有下表的 sqlite 数据库:
CREATE TABLE games (name text, date text, winloss int, gameid int, pointsfor int, pointsagainst int);
两个示例记录如下所示:
Anna A, 7/12/13, 0, 345, 56, 28
Barley B, 7/12/13, 1, 345, 28, 56
(Barley 的球队输了,Anna 的球队赢了。每场比赛每队都有几名球员。)我想创建一个查询,该查询将返回一个队中有 x 名球员和另一队有 y 名球员的所有比赛,加上这些球员的累积结果游戏。
我知道如何使用 perl 和 csv 文件来做到这一点,并且我相信我可以对 dbi 接口(interface)使用相同的方法。但是,我想了解如何仅使用 SQL 查询来创建此报告。我是 SQL 新手,我怀疑解决方案可能涉及使用 CASE WHEN 或 JOIN 旋转表来创建新表;但我不知道该怎么做。
此查询将返回所有玩家在同一支球队中并且获胜(或失败,取决于 winloss 的值)的所有游戏:
select gameid,date from games
where name in ('Anna A', 'Barley B') and winloss=1
group by gameid
having count(*)>1;
但我不知道如何概括该查询以返回与另一支球队的球员的比赛。
最佳答案
这将为您提供 A 和 B 战胜 C、D 和 E 的游戏的所有台词。
select *
from games
where gameid in
(select gameid from games
where name in ('Anna A', 'Barley B') and winloss=1
group by gameid
having count(*) = 2
intersect
select gameid from games
where name in ('Charly C', 'Dave D', 'Ed E') and winloss = 0
group by gameid
having count(*) = 3) ;
或者,您可以使用:
select *
from games where gameid in (
select gameid from games where name = 'Anna A' and winloss = 1 intersect
select gameid from games where name = 'Barley B' and winloss = 1 intersect
select gameid from games where name = 'Charly C' and winloss = 0 intersect
select gameid from games where name = 'Dave D' and winloss = 0 intersect
select gameid from games where name = 'Ed E' and winloss = 0
) ;
哪个最适合你。
然后您可以添加
sum
和 group by
得到累积的结果。
关于sql - SQL 查询中选择的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861822/