我从SQL开始,当我想运行一些查询时遇到问题。数据库有这两个表:
我想检索“id_equip”27和58的球队名称,以及两者之间的中场比赛的百分比。
到目前为止,我已经完成了:
SELECT j.id_eq_local ,
Avg(res_local)
FROM juga AS j
WHERE (
j.id_eq_local = 58
OR j.id_eq_local = 27)
AND (
res_local > res_visitant
OR res_local < res_visitant)
AND (
j.id_eq_visitant = 58
OR j.id_eq_visitant = 27)
GROUP BY (j.id_eq_local, j.id_eq_visitant);
但它没有给出结果:
巴塞罗那 - 57
皇马 - 28
这意味着:巴塞罗那赢得了57%的比赛,皇家马德里获得了28%的胜利,其余的则以平局结束。
数据库的简要说明:
表JUGA:
id_jornada =本周的身份
id_temp =本赛季的身份
id_lliga =联赛的ID(在这种情况下必须是“ESP”)
id_eq_local =本地团队的ID
id_eq_visitant =来宾团队的身份
res_local =本地团队成绩
res_vistitant =来宾团队成绩
表设备:
id_equip =团队的身份
nom_equip =团队名称
我想要的是什么:
提前谢谢。
答案 0 :(得分:3)
可以在聚合函数上使用postgre的filter
- 说明符,它将聚合函数考虑的行限制为满足特定条件的行。因此,我们可以比较同一查询中不同行集的计数:
select 'Real Madrid' as equip,
100*(count(*) filter (where (id_eq_local > id_eq_visitant and res_local > res_visitant) OR (id_eq_local < id_eq_visitant and res_local < res_visitant))) / count(*) as percentage
from juga
where id_eq_visitant IN (27,58)
and id_eq_local IN (27,58)
UNION
select 'Barcelona' as equip,
100*(count(*) filter (where (id_eq_local < id_eq_visitant and res_local > res_visitant) OR (id_eq_local > id_eq_visitant and res_local < res_visitant))) / count(*) as percentage
from juga
where id_eq_visitant IN (27,58)
and id_eq_local IN (27,58)
答案 1 :(得分:2)
我认为这样做会。
${propA${propB}}
答案 2 :(得分:0)
我认为这就是你要找的东西:
select (local.local_wins + guest.guest_wins) / (local.cnt + guest.cnt) as Team1,
(local.guest_wins + guest.local_wins) / (local.cnt + guest.cnt) as Team2
from
(select sum(case when res_local > res_visitant then 1 else 0 end) as local_wins, sum(case when res_visitant > res_local then 1 else 0 end) guest_wins, count(*) as cnt
from JUGA where id_local = 53 and id_guest = 17) local,
(select sum(case when res_local > res_visitant then 1 else 0 end) as local_wins, sum(case when res_visitant > res_local then 1 else 0 end) as guest_wins, count(*) as cnt
from JUGA where id_local = 17 and id_guest = 53) guest