包含三个不同表的SELECT语句

时间:2018-06-03 14:00:44

标签: sql postgresql select greatest-n-per-group

注意:我不确定如何标题,如果有人有更好的想法随时改变它。

我的数据库目前有以下表格(某些列和其他详细信息已从显示的命令输出中删除,但它们不相关):

webserver=> \d+ team

   Column    |          Type          |                     Modifiers                     | Storage  
-------------+------------------------+---------------------------------------------------+----------
 id          | integer                | not null default nextval('team_id_seq'::regclass) | plain     
 name        | character varying(255) | not null                                          | extended  
Indexes:
    "team_pkey" PRIMARY KEY, btree (id)
    "team_name" UNIQUE, btree (name)
Referenced by:
    TABLE "challengesolve" CONSTRAINT "challengesolve_team_id_fkey" FOREIGN KEY (team_id) REFERENCES team(id)

webserver=> \d+ challenge

       Column       |          Type          |                       Modifiers                        | Storage  
--------------------+------------------------+--------------------------------------------------------+----------
 id                 | integer                | not null default nextval('challenge_id_seq'::regclass) | plain     
 name               | character varying(255) | not null                                               | extended  
 points             | integer                | not null                                               | plain     
Indexes:
    "challenge_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "challengesolve" CONSTRAINT "challengesolve_challenge_id_fkey" FOREIGN KEY (challenge_id) REFERENCES challenge(id)

webserver=> \d+ challengesolve

    Column    |            Type             | Modifiers | Storage  
--------------+-----------------------------+-----------+---------
 team_id      | integer                     | not null  | plain   
 challenge_id | integer                     | not null  | plain   
Indexes:
    "challengesolve_pkey" PRIMARY KEY, btree (team_id, challenge_id)
    "challengesolve_challenge_id" btree (challenge_id)
    "challengesolve_team_id" btree (team_id)
Foreign-key constraints:
    "challengesolve_challenge_id_fkey" FOREIGN KEY (challenge_id) REFERENCES challenge(id)
    "challengesolve_team_id_fkey" FOREIGN KEY (team_id) REFERENCES team(id)

teamchallenge表应该是相当自我解释的。 challengesolve表是一个交集表,表明哪些团队已经解决了哪些挑战。

总之,我想找到得分最多的三支球队。我已经知道我可以通过像

这样的声明找到特定团队的积分数
SELECT SUM(challenge.points) AS points 
FROM challengesolve 
INNER JOIN challenge
ON challenge.id = challengesolve.challenge_id 
WHERE challengesolve.team_id = 1;

如何修改此查询以找到前三个团队?

1 个答案:

答案 0 :(得分:3)

  

简而言之,我想找到得分最多的三支球队。

您可以使用:

SELECT challengesolve.team_id,SUM(challenge.points) AS points 
FROM challengesolve 
INNER JOIN challenge
ON challenge.id = challengesolve.challenge_id 
GROUP BY challengesolve.team_id
ORDER BY points DESC
LIMIT 3;