SQL - Comment faire un comptage horizontal

Trucs & Astuces - SQL

AddThis Social Bookmark Button

 

Exemple de comptage horizontal avec une rupture sur le code produit :

 

select code,
    sum(case VILCLI when 'ANNECY' then 1 else 0 end) as LYON,
    sum(case VILCLI when 'PARIS' then 1 else 0 end) as PARIS,
    sum(case when VILCLI not in ('LYON','PARIS')
                then 1 else 0 end) as DIVERS
from clients
group by code   
order by code    

 

CODE   ANNECY   PARIS    DIVERS    
  A1        2         0           3    
  B2        1         0           3    
  B3        0         2           1