Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of Value column with case when and group by

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 !!

like image 244
pc_pyr Avatar asked May 20 '20 06:05

pc_pyr


People also ask

Can we use count and GROUP BY together?

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.

Can we use case when in GROUP BY?

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.

Can you do a count on a case statement in SQL?

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.


1 Answers

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
like image 104
dnoeth Avatar answered Oct 12 '22 14:10

dnoeth