我正在创建一个包含大量嵌套查询的SQL查询,我正在尝试使用CASE表达式,但它表现得非常奇怪。
这是我目前的询问:
select t.fpl_id, t.team_name,
sum(pf.points)as gwpts,
(
select sum(transfers_malus)
from gameweeks
where gameweeks.team_id = t.id and gameweeks.number = g.number
)as malus,
(
select sum(points)
from player_fixtures as pfix
where gw_number = g.number and pfix.player_id = CASE WHEN minutes_played > 0 THEN g.captain_id ELSE g.vice_captain_id END
)
as cpts,
(
select max(web_name)
from players
join player_fixtures on players.id = player_fixtures.player_id and gw_number = g.number
where players.id = CASE WHEN player_fixtures.minutes_played > 0 THEN g.captain_id ELSE g.vice_captain_id END
) as captain_name,
array_agg(p.id) as lineup
from teams as t
join gameweeks as g on t.id = g.team_id
join gameweeks_players as gp on gp.gameweek_id = g.id
join players as p on gp.player_id = p.id
join player_fixtures as pf on p.id = pf.player_id and pf.gw_number = g.number
where t.id = 1
group by t.id, g.id
order by g.number asc
我遇到问题的一点是,当我在做一个案例陈述时,看看其中一名队员(队长)是否还没有根据“minutes_played”进行比赛:
(select sum(points)
from player_fixtures as pfix
where gw_number = g.number and pfix.player_id = CASE WHEN minutes_played > 0 THEN g.captain_id ELSE g.vice_captain_id END
) as cpts
和
(
select max(web_name)
from players
join player_fixtures on players.id = player_fixtures.player_id and gw_number = g.number
where players.id = CASE WHEN player_fixtures.minutes_played > 0 THEN g.captain_id ELSE g.vice_captain_id END
) as captain_name,
当minutes_played确实大于0时,一切正常。但是,当它等于0时,它不会“返回”任何东西,并且在我的行中返回NULL。 minutes_played是一个整数,当我在player_fixtures上尝试使用以下脚本时,minutes_played = 0 my>评估工作,我得到了正确的“坏”。
DO LANGUAGE plpgsql $$
BEGIN
IF (select minutes_played from player_fixtures where gw_number = 19 and player_id = 266 ) > 0 THEN
RAISE NOTICE 'GOOD';
ELSE
RAISE NOTICE 'BAD';
END IF;
END;
$$;
我对这整个数据库的事情都很陌生,所以我可能犯了一个新手的错误,但我一直在尝试过去6小时而没有任何运气。有人能指出我正确的方向吗?
答案 0 :(得分:0)
问题在于,当没有匹配的行时,sum()
返回null,和不会与null进行比较。
相反,请使用exists()
,例如:
where exists(select * from player_fixtures
where gw_number = 19
and player_id = 266
and minutes_played > 0)
或者您可以在存储过程中使用if exists(...) then
。