使用SQLite

时间:2017-12-11 02:02:02

标签: sql sqlite

我有一个名为Player_Plays_In的SQLite3表,其关系如下:

Player_Plays_In(player_id, match_id, position, points_scored)player_idmatch_id是主要关键。表格中的一些样本数据如下所示:

sample data.

我需要找到得分最多的player_id。给定的player_id会在表格中多次出现,对于他们玩的每场比赛都会出现一次。我可以使用player_idGROUP BY对点进行求和,然后找到 a max,带有以下查询:

SELECT ID, MAX( points ) 
FROM (
      SELECT player_plays_in.player_id AS ID, 
          SUM(player_plays_in.points_scored) AS points
      FROM player_plays_in
      WHERE player_plays_in.points_scored > 0
      GROUP BY player_plays_in.player_id
      );

但这只返回ID,MAX(点)的第一个实例。

Single row being returned

也就是说,我知道有三个独立的球员,他们都得到了30分。查询仅返回第一个查询。任何帮助,将不胜感激。

3 个答案:

答案 0 :(得分:1)

使用CTE和子查询:

with p as (
      SELECT ppi.player_id AS ID, SUM(ppi.points_scored) AS points
      FROM player_plays_in ppi
      WHERE ppi.points_scored > 0
      GROUP BY ppi.player_id
     )
select p.*
from p
where p.points = (select max(p2.points) from p p2);

答案 1 :(得分:0)

试试这个,

SELECT ID, Points 
FROM (
      SELECT player_plays_in.player_id AS ID, 
          SUM(player_plays_in.points_scored) AS points
      FROM player_plays_in
      WHERE player_plays_in.points_scored > 0
      GROUP BY player_plays_in.player_id
      ) AS D
WHERE Points = (SELECT MAX( points ) 
    FROM (
          SELECT player_plays_in.player_id AS ID, 
              SUM(player_plays_in.points_scored) AS points
          FROM player_plays_in
          WHERE player_plays_in.points_scored > 0
          GROUP BY player_plays_in.player_id
          ));

答案 2 :(得分:0)

感谢帮助。 Gordon Linoff和DineshDB的建议都奏效了。我昨晚能够通过它来实现它:

{{1}}