1

我有一个任务,我需要编写一个 SQL 查询,该查询将检索球员号码和为队长支付的罚金总额,这些球员的罚金总额超过 80 英镑。

我有三张桌子

球员(球员编号、姓名、姓名首字母、街道、城镇、邮政编码)

团队(teamNo, playerNo ,部门)

处罚(paymentNo,playerNo,penDate,金额)

粗体字表示主键。Teams 表中的 playerNo 表示球队队长。

我不知道如何加入三个表。但我的尝试是:

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;

这是正确的吗?

4

4 回答 4

4
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....
于 2012-05-17T19:18:00.187 回答
1

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?

于 2012-05-17T18:54:41.410 回答
0

如果一名球员不能担任多个球队的队长,是的,您的查询是正确的。它只需要您替换GROUP BY playerNoGROUP BY p1.playerNo.

但如果一名球员可以担任多支球队的队长,则会返回错误的结果。无论如何,这将为您提供正确的答案:

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;
于 2012-05-17T21:25:46.800 回答
0
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 ;
于 2013-03-13T12:15:55.837 回答