sql >> Base de Datos >  >> RDS >> Mysql

Consulta SQL para ordenar y lograr un conteo único

Puede usar el agregado condicional de la siguiente manera:

Select stage, 
       count(case when year = 2019 then 1 end) as year2019, 
       count(case when year = 2020 then 1 end) as year2020 
From
(Select t.*, 
        row_number() over (partition by customer, year
          order by case when dealstage = 'won' the 1 
                        When dealstage = 'contacted' then 2
                       else 3 end) as rn
    From your_table t) t
Where rn = 1
Group by stage;