Multiple counts in different colums

15 views Asked by At

i have this little problem i´m unable to fix.

i have this query:

Select DATE_FORMAT(fecha, '%M')as Month, count( distinctrow terminal ) as NT2023 FROM journal where operacion = 'venta' and year(fecha)='2022' GROUP by DATE_FORMAT(fecha, '%m')

and i get 2 columns, 1 with the month, and another with the amount of terminals active for 2022

i wolud like to obtain 2 more columns for years 2023 and 2024, any clue?

this is what i get:

Month NT2022
Februery 5
March 8
April 24
May 29
June 29
July 31
August 36
September 51
October 60
November 66
December 71

this is what i want to get :

Month NT2022 NT2023 NT2024
Januery 0 73 158
Februery 5 83 161
March 8 83 168
April 24 91 170
May 29 93 173
June 29 105 180
July 31 113 183
August 36 122 189
September 51 127 193
October 60 134 201
November 66 145 203
December 71 152 205
1

There are 1 answers

1
Pedro Couto On

Finally found the way:

SELECT  DATE_FORMAT(fecha, '%M') as Month,  
    COUNT(DISTINCT CASE WHEN year(fecha) = '2022' THEN Terminal END) AS NT2022,
    COUNT(DISTINCT CASE WHEN year(fecha) = '2023' THEN Terminal END) AS NT2023,
    COUNT(DISTINCT CASE WHEN year(fecha) = '2024' THEN Terminal END) AS NT2024
From journal where operacion = 'venta' group by DATE_FORMAT(fecha, '%m') order by month(fecha)