如何进行sql查询以获得所需的结果?

uxh89sit  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(335)

我需要一些帮助来了解如何做到这一点(一个简化的案例):有三张table:运动员、裁判和服装:

--
create table t_athletes
(
    id number,
    name varchar(100)
);

--
create table t_referees
(
    id number,
    name varchar(100)
);

--
create table t_rating
(
    athlete_id number,
    referee_id number,
    val number
);

insert into t_athletes values (1, 'Smith');
insert into t_athletes values (2, 'Jones');
insert into t_athletes values (3, 'Davis');

insert into t_referees values (100, 'Ref Scott');
insert into t_referees values (200, 'Ref Tiger');

insert into t_rating values (1, 100, 2);
insert into t_rating values (1, 200, 5);

insert into t_rating values (2, 100, 5);
insert into t_rating values (2, 200, 4);

insert into t_rating values (3, 100, 1);
insert into t_rating values (3, 200, 3);

我需要得到这样的结果:

| Ref Scott | Ref Tiger
--------+-----------+----------
Smith   |         2 |         5
Jones   |         5 |         4
Davis   |         1 |         3

裁判员的数量和运动员的数量没有给出-可能是两个或10个
怎么做?

xwbd5t1u

xwbd5t1u1#

要在固定的仲裁人列表上进行透视,您可以加入和条件聚合:

select 
    ah.name, 
    sum(case when re.name = 'Ref Scott' then ra.val else 0 end) ref_scott,
    sum(case when re.name = 'Ref Tiger' then ra.val else 0 end) ref_tiger
from t_athletes ah
inner join t_rating ra   on ra.athlete_id = ah.id
inner join t_referees re on re.id = ra.referee_id
group by ah.id, ah.name
order by ah.name desc

db小提琴演示:

NAME  | REF_SCOTT | REF_TIGER
:---- | --------: | --------:
Smith |         2 |         5
Jones |         5 |         4
Davis |         1 |         3

相关问题