Table:
x
Date Id Value
2019-02-09 a1 ab
2019-01-12 a2 cd
2019-12-12 a1 ab
2017-07-23 a1 ab
2018-12-09 a1 ab
2018-12-28 a1 cd
2016-11-09 a2 cd
2016-05-19 a2 ab
Output:
Id Max-Min
a1 1
a2 -1
The aim is to create Max_year_count-Min_year_count per Id
.
For example, calculation in Value column
:
(count of occurrence of value in max_year with group by Id)-(count of occurrence of value in min_year with group by Id)
Thanks !!
Advertisement
Answer
Oracle supports FIRST/LAST for aggregates:
SELECT id,
-- latest year's count
Count(*) KEEP (Dense_Rank LAST ORDER BY Extract(YEAR From "Date"))
-- oldest year's count
- Count(*) KEEP (Dense_Rank FIRST ORDER BY Extract(YEAR From "Date"))
FROM DATA
GROUP BY Id