I'm having trouble formulating a query for the following problem:
For pair values that have a certain score, how do you group them in way that will only return distinct pair values with the best respective scores?
For example, lets say I have a table with the following row values:
(t1,p1,65)
(t1,p2,60)
(t1,p3,20)
(t2,p1,60)
(t2,p2,59)
(t2,p3,15)
The first two columns indicate the pair values and the third column represents the pair score.The best score is (t1,p1,65)
. Since t1 and p1 are now used, I want to exclude them from further analysis.
The next best score is (t2,p2,59)
. Even though (t1,p2)
has a score of 60, I want to exclude it because "t1" has already been used. (t2,p1)
also has a score of 60, but since p1 is also already used, this pair is excluded.
This results in the distinct pair score values of:
(t1,p1,65)
(t2,p2,59)
Is there any way to generate this result with just a query? I've tried to think of ways of grouping and partitioning the results, but since there has to be some accounting of values already used according to score rank, I'm finding this very difficult to approach.
EDIT:
To generate the data:
with t(t, p, score) as (
(values ('t1','p1',65),
('t1','p2',60),
('t1','p3',20),
('t2','p1',60),
('t2','p2',59),
('t2','p3',15)
))
select t.* from t;