在PL / SQL中获取用户分数

时间:2017-03-23 14:14:58

标签: sql plsql

所以我的困境是试图找出国际象棋游戏中用户的总分。该特定用户可以是白人用户还是黑人用户。这是代码:

create table user(
u_id int,
u_name varchar(50),
u_grade int,
u_rating int,
primary key (u_id));

create table competition(
c_id int,
c_name varchar(255),
c_date date,
primary key (c_id));

create table matchup(
b_id int,
c_id int, 
turn int, 
x_pid int, 
y_pid int, 
x_score number, 
y_score number, 
primary key(b_id,c_id,turn),
foreign key(c_id) references competition,
foreign key(x_pid) references user,
foreign key(y_pid) references user);

insert into matchup values(1,1,1,1,2,0,1);
insert into matchup values(2,1,1,3,4,0.5,0.5);
insert into matchup values(11,1,1,5,6,1,0);
insert into matchup values(12,1,1,7,8,0,1);
insert into matchup values(1,1,2,2,3,0,1);
insert into matchup values(2,1,2,4,1,1,0);
insert into matchup values(11,1,2,8,5,1,0);
insert into matchup values(12,1,2,6,7,0.5,0.5);

让我们说,为了我们的目的,1是鲍勃的u_id。我怎么能根据他作为y_pid玩的时候以x_pid +的比分得到的得分总数?这是我到目前为止所做的,

CURSOR c1 IS SELECT (SUM(x_score) + SUM(y_score)) AS total_score FROM matchup JOIN user u1 ON matchup.y_pid = u1.u_id
JOIN user u2 ON matchup.x_pid = u2.u_id JOIN competition ON matchup.c_id = competition.c_id WHERE
(u1.u_name = 'Bob' OR u2.u_name = 'Bob') AND  commpetition.c_name = 'Wonderland';

此查询似乎为我尝试的所有用户提供相同的输出,数字2为总数。我究竟做错了什么?因为对于鲍勃来说,总得分应为0,因为他没有赢得任何比赛(0分是没有胜利,0.5分是平局,1分是胜利)

1 个答案:

答案 0 :(得分:1)

您的查询简化形式:

select (sum(x_score) + sum(y_score)) as total_score
  from matchup
 where x_pid = 1
    or y_pid = 1;

它计算鲍勃的得分和对手得分的总和。所以你需要将彼此分开。

示例1:

select (sum(decode(x_pid, 1, x_score, 0)) + sum(decode(y_pid, 1, y_score, 0))) as total_score
  from matchup
 where x_pid = 1
    or y_pid = 1;

示例2:

select sum(s) as total_score
  from (select sum(x_score) s
          from matchup
         where x_pid = 1
        union all
        select sum(y_score) 
          from matchup
         where y_pid = 1);