1

考虑一个名为 的假想表的以下表结构score

player_name   |player_lastname   |try   |score   
 primary key: (player_name,player_lastname,try)

(不讨论表模式,它只是一个例子)

该表包含所有玩家的分数 - 每个玩家应该能够玩一次或两次。现在,我怎样才能只获取每个玩家最后一次尝试的数据(即,对于那些玩了不止一次的人来说,第一次尝试应该被忽略)?

我试图实现的一个例子:

player_name,player_lastname,try,score
=====================================
bart, simpson,1,250
lisa,simpson,1,150
lisa,simpson,2,250
homer,simpson,1,300
homer,simpson,2,350
maggi,simpson,1,50

结果应该是:

player_name,player_lastname,try,score
=====================================
bart, simpson,1,250
lisa,simpson,2,250
homer,simpson,2,350
maggi,simpson,1,50
4

5 回答 5

3

一种选择是JOIN使用子查询将表添加到自身MAX

select s.*
from score s
  join (
    select max(try) maxtry, player_name, player_lastname
    from score
    group by player_name, player_lastname
    ) s2 on s.player_name = s2.player_name
      and s.player_lastname = s2.player_lastname
      and s.try = s2.maxtry

根据您的数据库,您可能能够利用分析功能,例如ROW_NUMBER()这会使这更容易。这是另一个要演示的小提琴。


既然您使用的是postgresql,那么您应该能够使用分析ROW_NUMBER()功能。这也应该有效:

select *
from (
    select try, player_name, player_lastname, score, 
      Row_Number() Over (Partition By player_name, player_lastname order by try desc) rn
    from score
    ) s
where rn = 1

顺便说一句——我会考虑添加一个 player_id 作为主键。

于 2013-05-29T22:09:54.297 回答
3

这可能会有最好的表现

select distinct on (player_name, player_lastname)
    player_name, player_lastname, try, score
from score
order by 1, 2, 3 desc
于 2013-05-29T23:22:00.457 回答
2

Rank 函数可以解决这个问题:

SELECT player_name,player_lastname,TRY,score
FROM  (SELECT player_name,player_lastname,TRY,score,RANK() OVER (PARTITION BY player_name, Player_Lastname ORDER BY TRY DESC)AS try_rank
       FROM score
       )sub
WHERE try_rank = 1

我假设“尝试”是可以是 1/2 的数字。

编辑,忘记了 Partition BY

于 2013-05-29T22:04:08.717 回答
0

试试这个:

Sel player_name,
player_lastname,
try,
score 
from score where try = 2 or
try = 1 and
(player_name,player_lastname) not in
(sel player_name,player_lastname from score where try=2);
于 2013-05-29T22:03:20.100 回答
0
SELECT player_name,player_lastname,try,score
FROM scores sc
WHERE NOT EXISTS (
  SELECT *
  FROM scores nx
  WHERE nx.player_name = sc.player_name
  AND nx.player_lastname = sc.player_lastname
  AND nx.try > sc.try
  );
于 2013-05-29T23:14:36.187 回答