Table:
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 !!
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.
The function Countifs can often be implemented with an and condition in the case expression. The function counta can be implemented with a case expression as well. For that, SQL makes a distinction between empty strings and the null value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With