在SQLite中选择每年的最大总和

时间:2016-05-20 01:40:05

标签: sql sqlite select

我有一个SQLite数据库,可以跟踪棋盘游戏的信息(名称,年份出版,机制,出版商,在www.boardgamegeek.com上拥有它的人数,以及boardgamegeek当前的游戏等级)。架构是:

Schema for database

我有兴趣每年为特定的出版商提供最受欢迎的机械师(拥有最多份数的机械师)。我当前的查询是:

select games.year as yr, mechanics.name as mech, sum(collection.owned) as sm
 from games 
 inner join gamemech on games.bggid = gamemech.bggid
 inner join mechanics on gamemech.mechid = mechanics.mechid
 inner join gamepub on gamepub.bggid = games.bggid
 inner join publishers on publishers.pubid = gamepub.pubid
 inner join collection on collection.bggid = games.bggid
 where publishers.name like '%stronghold%'
 group by yr, mech order by yr limit 20;

返回:

1974|Commodity Speculation|1460
1974|Dice Rolling|1460
1974|Tile Placement|1460
1982|Action Point Allowance System|16111
1982|Dice Rolling|16111
1982|Modular Board|16111
1982|Secret Unit Deployment|16111
1985|PaperandPencil|1949
1991|Auction/Bidding|1266
1992|Grid Movement|1704
1992|Pickup and Deliver|1704
2011|Action Point Allowance System|7943
2011|Area Control / Area Influence|174
2011|Area Movement|3607
2011|Auction/Bidding|174
2011|Card Drafting|5133
2011|Deck / Pool Building|3768
2011|Dice Rolling|2385
2011|Hand Management|5663
2011|Line Drawing|2141

我真正感兴趣的只是年份,机械师和每年所有机械师拥有最高金额的所有副本。像这样(但是可以打破关系):

1974|Commodity Speculation|1460
1982|Action Point Allowance System|16111
1985|PaperandPencil|1949
1991|Auction/Bidding|1266
1992|Grid Movement|1704
2011|Action Point Allowance System|7943

我想我可能在查询中需要另一个select语句,但我似乎无法让它工作。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

解决方案只是打击了我。如果你发现自己在这里,我就是这样做的:

我基本上想要获得每组的最大值(sum())。你需要做的第一件事是找出包含所有数据的查询(这是我的第一个查询)。对我来说,它是:

select games.year as yr, mechanics.name as mech, sum(collection.owned) as sm
 from games 
 inner join gamemech on games.bggid = gamemech.bggid
 inner join mechanics on gamemech.mechid = mechanics.mechid
 inner join gamepub on gamepub.bggid = games.bggid
 inner join publishers on publishers.pubid = gamepub.pubid
 inner join collection on collection.bggid = games.bggid
 where publishers.name like '%stronghold%'
 group by yr, mech order by yr limit 20;

这回归的主要问题是什么。接下来,我们要从中进行选择。我对以下内容感兴趣:

games.year, mechanics.name, max(sm)

诀窍是第一个查询中的每个表都需要命名(对我来说这是yr,mech和sm),以便您以后可以加入它。最后的查询是:

Select games.year, mechanics.name, max(sm) from (
select games.year as yr, mechanics.name as mech, sum(collection.owned) as sm
 from games 
 inner join gamemech on games.bggid = gamemech.bggid
 inner join mechanics on gamemech.mechid = mechanics.mechid
 inner join gamepub on gamepub.bggid = games.bggid
 inner join publishers on publishers.pubid = gamepub.pubid
 inner join collection on collection.bggid = games.bggid
 where publishers.name like '%stronghold%'
 group by yr, mech)
inner join games on games.year = yr
inner join mechanics on mechanics.name = mech
group by yr;

我希望这是有道理的!