Sql 带条件的聚合?
我试图根据条件if玩家id(Gary)进行聚合 得分高于、等于或低于玩家id(“其他”) 我的模式已更改Sql 带条件的聚合?,sql,postgresql,database-schema,Sql,Postgresql,Database Schema,我试图根据条件if玩家id(Gary)进行聚合 得分高于、等于或低于玩家id(“其他”) 我的模式已更改 players(player_id, name) matches(match_id, home_team(player_id), away_team(player_id) ) outcome(outcome_id, match_id, home_score:integer, away_score:integer 输出自: select m.match_id, p.name AS ho
players(player_id, name)
matches(match_id, home_team(player_id), away_team(player_id) )
outcome(outcome_id, match_id, home_score:integer, away_score:integer
输出自:
select m.match_id, p.name AS home_team, p1.name AS away_team, o.home_score, o.away_score
from players p
inner join matches m on (p.player_id = m.home_team)
inner join players p1 on (p1.player_id = m.away_team)
inner join outcomes o on (m.match_id = o.match_id);
match_id | player_id | player_id | home_score | away_score
----------+-----------+-----------+------------+------------
1 | 1 | 2 | 1 | 2
2 | 2 | 1 | 1 | 3
3 | 3 | 1 | 3 | 2
想要的输出:
player_id | Wins | Draws | Losses
-------------+------+-------+--------
1 | 1 | 0 | 2
2 ... | ... | .. | ...
我的模式可以更改
编辑(SQLFIDLE):对于没有子查询和联合的解决方案:
我会使用
UNION ALL
两次获取每个结果,一次用于主场
,一次用于客场
玩家。第二次主客场得分
/客场得分
应切换,以获得客场球员的正确总和
select
d.player_id,
d.name,
sum(d.home_score > d.away_score) as wins,
sum(d.home_score = d.away_score) as draws,
sum(d.home_score < d.away_score) as loses
from (
select p.player_id, p.name, o.home_score, o.away_score
from players p
join matches m on p.player_id = m.home_team
join outcomes o on o.match_id = m.match_id
union all
select p.player_id, p.name, o.away_score as home_score, o.home_score as away_score
from players p
join matches m on p.player_id = m.away_team
join outcomes o on o.match_id = m.match_id) d
group by d.player_id, d.name
sqlFiddle演示:啊,对于模棱两可的问题,很抱歉,这不重要!重点是获得每个玩家@Filipe SilvaCan的赢、输和平局的数量。您可以使用原始表格样本数据添加一个吗?可以@FilipeSilva@FilipeSilvaThis不会像预期的那样返回结果。我担心,这应该是因为Marcin的answare@wolphindect,我忘记了反向关系:)我添加了一个修改版本。我个人不是工会的粉丝,一切都很好!,感谢您提供的解决方案,我从这两个例子中学到了很多!我也想把你的answare作为解决方案,但marcin“更快地”解决了它,在生产中,我想我会使用你的解决方案,尽管@wolph谢谢!这非常有帮助,并得到了预期的结果,尽管我不知道我的模式是否正确地设置为应答此类查询@马金库拉泽克
PLAYER_ID WINS DRAWS LOSSES
1 1 0 2
2 1 0 1
3 1 0 0
4 0 0 0
5 0 0 0
select
d.player_id,
d.name,
sum(d.home_score > d.away_score) as wins,
sum(d.home_score = d.away_score) as draws,
sum(d.home_score < d.away_score) as loses
from (
select p.player_id, p.name, o.home_score, o.away_score
from players p
join matches m on p.player_id = m.home_team
join outcomes o on o.match_id = m.match_id
union all
select p.player_id, p.name, o.away_score as home_score, o.home_score as away_score
from players p
join matches m on p.player_id = m.away_team
join outcomes o on o.match_id = m.match_id) d
group by d.player_id, d.name
PLAYER_ID NAME WINS DRAWS LOSES
1 Gary 1 0 2
2 Tom 1 0 1
3 Brad 1 0 0