Я столкнулся с этим вопросом в интервью.Я должен был получить заработанные очки, счет выигрыша, счет проигрыша, счет ничьи в команде.Мой запрос дает мне правильный результат, но я ищу способ обойти запрос.Любая помощь?
Определенные условия, которые я рассмотрел в моем запросе:
1. If a team wins i am allocating 3 as match point and 2 if a team loses
2. If the match is a tie (when winner is null) i am awarding 1 point to each team.
DDL и DML:
create table match_t(team1 varchar(20),team2 varchar(20),Winner varchar(20));
insert into match_t values('India','Pakistan','India');
insert into match_t values('India','Srilanka','India');
insert into match_t values('Srilanka','Pakistan','Pakistan');
insert into match_t values('Srilanka','India','Srilanka');
insert into match_t values('Pakistan','Srilanka','Srilanka');
insert into match_t values('Pakistan','India','India');
insert into match_t values('India','Srilanka','India');
insert into match_t values('Pakistan','India',null);
insert into match_t values('Srilanka','Pakistan',null);
Commit;
Мой ответ на проблему:
with abc as(
select team1 as host,team2 as guest,case when team1=winner
then 1 else 0 end as host_w,
case when team2 = winner
then 1 else 0 end as guest_w
from match_t), bac as(
select host,3 as m_point,1 as host_win,0 as guest_win,0 as match_d from abc where host_w > guest_w
union all
select guest,3 as m_point,0 as host_win,1 as guest_win,0 as match_d from abc where host_w < guest_w
union all
select guest,2 as m_point,0 as host_win,0 as guest_win,0 as match_d from abc where host_w > guest_w
union all
select host,2 as m_point,0 as host_win,0 as guest_win,0 as match_d from abc where host_w < guest_w
union all
select host,1 as m_point,0 as host_win,0 as guest_win, 1 as match_d from abc where host_w = guest_w
union all
select guest,1 as m_point,0 as host_win,0 as guest_win, 1 as match_d from abc where host_w = guest_w
),
cad as(
select host as team,sum(m_point) as match_p,sum(host_win+guest_win) as win_c,
sum(match_d) as match_d_c
from bac group by host),
dac as(select sum(lost_c) as lost_c,team from (select count(*) as lost_c,host as team from abc where host_w=0 and guest_w <> 0
group by host
union all
select count(*) as lost_c,guest as team from abc where guest_w=0 and host_w <> 0
group by guest) group by team)
select a.team,a.match_p,a.win_c,b.lost_c,a.match_d_c,a.win_c+b.lost_c+a.match_d_c as no_match from cad a, dac b where a.team=b.team
Это дает мне правильный результат (см. Ниже).Но я ищу способ, как легко я могу получить это без написания такого длинного кода
