我有一个带有下表的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接口相同的方法。但是,我想学习如何仅使用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;
但我不知道如何推广该查询以与其他团队的玩家一起返回游戏。
答案 0 :(得分:0)
这样的事情可能有所帮助:
where name in ('Anna A', 'Barley B')
更改为
where name in (SELECT DISTINCT Player FROM games)
答案 1 :(得分:0)
这将为您提供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
来获得累积结果。