简体   繁体   English

SQL查询,联接多个表,Oracle

[英]SQL query, join multiple tables, Oracle

I have an assignment where I need to write a SQL Query that would retrieve the player number and the total amount paid in penalties for players who are captains and have paid more than £80 in total for penalties. 我有一个作业,我需要编写一个SQL查询,该查询将检索作为队长且支付罚金总额超过80英镑的球员的球员人数和罚金总额。

I've got three tables 我有三张桌子

Players ( playerNo , name, initials, street, town, postcode) 玩家( playerNo ,姓名,名字缩写,街道,城镇,邮政编码)

Teams ( teamNo , playerNo, division) 团队( teamNo ,playerNo,分区)

Penalties ( paymentNo , playerNo, penDate, amount) 罚款( 付款编号 ,玩家编号,笔期,金额)

bold text indicates the primary key. 粗体字表示主键。 The playerNo in Teams table indicates the team captain. Teams表中的playerNo表示队长。

I don't know how to join three tables. 我不知道如何加入三个表。 But my attempt at this is: 但是我对此的尝试是:

SELECT p1.playerNo, SUM(p2.amount)
FROM Players p1 INNER JOIN Teams t
   ON p1.playerNo = t.playerNo 
JOIN penalties p2
   ON p2.playerNo = p1.playerNo
GROUP BY playerNo
HAVING SUM(p2.amount) > 80;

Is any of this correct? 这是正确的吗?

SELECT a.playerNo, a.playerName, SUM(c.amount) as amount, b.teamNo as Team
FROM players a, teams b, penalties c
WHERE a.playerNo = b.playerNo and a.playerNo = c.playerNo
Group By a.playerNo, c.teamNo
Having sum....

Your query appears to be correct to return what you want. 您的查询似乎是正确的返回您想要的。 It does open the question of what to do if the same player is captain of more than one team, but that probably does not happen. 它确实提出了一个问题,即如果同一位球员是一支以上球队的队长,该怎么办,但这可能不会发生。

Do you want comments on the database structure? 您是否需要有关数据库结构的注释?

If a player cannot be a captain to more than one team, yes, your query is correct. 如果一个玩家不能担任多个团队的队长,是的,您的查询是正确的。 It only needs you to replace GROUP BY playerNo with GROUP BY p1.playerNo . 它只需要用GROUP BY playerNo替换GROUP BY playerNo GROUP BY p1.playerNo

But if a player can be the captain of more than one team, it will return wrong results. 但是,如果一名球员可以担任多支球队的队长,那么它将返回错误的结果。 This will give you a correct answer, in any case: 无论如何,这将为您提供正确的答案:

SELECT p1.playerNo, SUM(p2.amount)
FROM Players p1 
  JOIN penalties p2
    ON p2.playerNo = p1.playerNo
WHERE EXISTS
      ( SELECT *
        FROM Teams t
        WHERE p1.playerNo = t.playerNo
      ) 
GROUP BY p1.playerNo
HAVING SUM(p2.amount) > 80;
select captaion_number , sum (amount) total_amount 
from (select t.playes.no   captaion_number , p.amount   amount 
from teams t ,  Penalties p
 where t.player_no = p.player_no ) 
group by captaion_number 
having total_amount > 80 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM