Question

I would like to extract from a table of results over time a list of maximums at the time when values can fluctuate up or down. For example a cricket highscore database would have many results but I want to list off which batsman had the highest one-day score against the dates on which that record was achieved.

I haven't been able to find a pattern for this type of query although a CTE checking the previous row seems close. Can someone help with the pattern name or an example of an efficient way of achieving this query?

example data

Value | date
1| 1/1/1970
2| 2/1/1970
1| 3/1/1970
2| 4/1/1970
1| 5/1/1970
3| 6/1/1970
10| 22/1/1970
4 | 1/12/1970
7 | 22/5/1975

expected result

Value | date
1|  1/1/1970
2|  2/1/1970
3|  6/1/1970
10| 22/1/1970

I'm starting to think a self join would work fine.

Was it helpful?

Solution

It can be done by simply LEFT JOINing the row with all the previous one and checking if max(value) of those is smaller than in the current row (or NULL for the first row)

SELECT t1.value
       ,t1.date
FROM Table1 AS t1
  LEFT JOIN Table1 AS t2
    ON t1.date > t2.date
GROUP BY 
  t1.id
HAVING
  max(t2.value) IS NULL 
  OR max(t2.value) < t1.value
ORDER BY t1.date;

Fiddle

OTHER TIPS

If I understand the data and results, you seem to want the first day that a particular value was hit. You would do this using aggregation, but with the min() function:

select value, min(date) as date
from table t
group by value;

At the very least, this will give you the desired results in the question.

EDIT:

So you want the first date of a cumulative max. You can get this too.

select cummax, min(date) as date
from (select date, max(value) over (order by date) as cummax
      from table t
     ) t
group by cummax;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top