Questo è ciò che devi fare:
select gender,
count(case when age between 0 and 20 then 1 else null end) Age_0_20,
count(case when age between 21 and 40 then 1 else null end) Age_21_40
from yourtable
group by gender
Regolare di conseguenza :)
Update, con chiarimenti
Nota che COUNT
funzione di aggregazione conta solo non -valori nulli. Pertanto, i valori else
nello case
devono essere NULL
. Il valore When
restituisce 1
ma potrebbe essere qualsiasi valore non nullo.
Alcune persone implementano questo utilizzando SUM
:
select gender,
sum(case when age between 0 and 20 then 1 else 0 end) Age_0_20,
sum(case when age between 21 and 40 then 1 else 0 end) Age_21_40
from yourtable
group by gender
Il risultato sarà assolutamente la stessa.
fonte
2012-04-02 16:12:30
Nota. So come recuperare tutti i dati. Ma voglio farlo usando l'ottimizzazione – Thompson
+1 Grazie per aver mostrato chiaramente l'input e l'output desiderato. – pilcrow
@pilcrow: Grazie. – Thompson