sql - SQL 查询中选择的语法

标签 sql sqlite

我有一个带有下表的 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
    ) ;

哪个最适合你。

然后您可以添加 sumgroup by得到累积的结果。

关于sql - SQL 查询中选择的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861822/

相关文章:

mysql - SQL如何更新左连接表?

多边形内的SQL Geography点在ST​​Intersect上不返回true(但使用Geometry返回true)

java - SQLite 更新或插入,而不是更新插入

Android - 在设备上查看 SQLite 数据库?

sql - Postgres 数据库大小命令

sql - 没有 XML 路径的逗号分隔列

javascript - Firefox 扩展的 "Extension Storage"的数据存储在哪里?

java - 如何在android中找到特定的数据库和表是否已经存在

java - SQLite 中的弱外键可能吗?

mysql - 根据 Woocommerce 中的日期批量更改订单状态