与多个ID的聚合/关联

时间:2017-01-26 18:44:51

标签: sql

我有2个表usr和rslt如下。

enter image description here

我想获得如下输出。

enter image description here

我已尝试过以下查询以获得总胜利和奖金丢失

SELECT    tab1.id
       , tab1.wins
       , tab2.loos
FROM
        (SELECT u1.ID
             , COUNT(r1.WINNER) wins
         FROM   rslt r1
             , usr u1
         WHERE  (u1.ID = r1.WINNER)
         GROUP BY u1.ID) tab1
       ,
        (SELECT u2.ID
             , COUNT(r2.Looser) loos
         FROM   rslt r2
             , usr u2
         WHERE  (u2.ID = r2.Looser)
         GROUP BY u2.ID) tab2
WHERE tab1.ID = tab2.id;

2 个答案:

答案 0 :(得分:0)

这可以使用相关查询来完成,如果usr表中每行运行每个查询,那么性能可能会很差,但是,你应该明白这一点。

   select 
      id, name, 
      (select count(*) c
       from rslt
       where
         (rslt.sender = usr.id or rslt.receiver = usr.id) and
         rslt.winner = usr.id) wins, 
      (select count(*) c
       from rslt
       where
         (rslt.sender = usr.id or rslt.receiver = usr.id)) played, 
      (select count(*) c
       from rslt
       where
         (rslt.sender = usr.id or rslt.receiver = usr.id) and
         rslt.looser = usr.id) lost, 
      (select count(*) c
       from rslt
       where
         (rslt.sender = usr.id or rslt.receiver = usr.id) and
         rslt.tie <> 'T') tie
    from usr;

运行查询时的结果:

enter image description here

下面的表格创建DML,如果有人想要摆弄

create table usr(id number,name varchar(10));

create table rslt (id number,sender number, receiver number,winner number,looser number, tie varchar(1));

insert into usr values(1,'Prince');

insert into  usr values(2,'Subham');

insert into usr values(3,'3');

insert into rslt values(1,1,2,2,1,'T');

insert into rslt values(2,2,3,3,2,'T');

答案 1 :(得分:0)

以下是如何在不使用大量相关查询的情况下完成此操作,这可能更难以正确优化:

SELECT
    u.ID
    ,u.NAME
    ,SUM(CASE WHEN r.SENDER = u.ID THEN 1 else 0 END + CASE WHEN r.RECEIVER = u.ID THEN 1 ELSE 0 END) as 'TotalPlayed'
    ,SUM(CASE WHEN r.WINNER = u.ID THEN 1 ELSE 0 END) as 'TotalWins'
    ,SUM(CASE WHEN (r.SENDER = u.ID OR r.RECEIVER = u.ID) AND r.WINNER <> u.ID THEN 1 else 0 END) as 'TotalLost'
    ,SUM(CASE WHEN (r.SENDER = u.ID OR r.RECEIVER = u.ID) AND r.TIE <> 'T' THEN 1 else 0 END) as 'TotalTie'
FROM USR u
LEFT JOIN RSLT r
ON u.ID = r.SENDER OR u.id = r.RECEIVER
GROUP BY u.ID, u.NAME
ORDER BY u.ID

这适用于SQL Server,我认为它应该适用于Oracle(您似乎正在使用它)

输出:

id          name       TotalPlayed TotalWins   TotalLost   TotalTie
----------- ---------- ----------- ----------- ----------- -----------
1           Prince     1           0           1           0
2           Subham     2           1           1           0
3           3          1           1           0           0
4           4          0           0           0           0
5           5          0           0           0           0
6           6          0           0           0           0
7           7          0           0           0           0
8           8          0           0           0           0