SQL (DB2) Restituisce più conteggi condizionali in una singola query
Domanda
Sto provando a selezionare più riepiloghi condizionali in un risultato di una singola tabella su un database basato su DB2.
Esempio:
SELECT COUNT(FOO) FROM T1 WHERE T1.A=1 AS A_COUNT,
SELECT COUNT(FOO) FROM T1 WHERE T1.B=2 AS B_COUNT
Ext...
Qualsiasi aiuto è apprezzato.
Soluzione
Questo conterà il verificarsi di ogni condizione:
select sum(case when t1.a = 1 then 1 else 0 end) as A_COUNT
, sum(case when t1.b = 2 then 1 else 0 end) as B_COUNT
from t1
where t1.a = 1
or t1.b = 2
Altri suggerimenti
select count(case when t1.a = 1 then foo else null end) as A_COUNT
, count(case when t1.b = 2 then foo else null end) as B_COUNT
from t1
where t1.a = 1
or t1.b = 2
Dove la clausola è facoltativa in senso stretto ma può aiutare le prestazioni. Inoltre " else null " è implicito quando la clausola else viene omessa in modo da poterlo tranquillamente escludere.
select count(foo)
from t1
where a = 1
union
select count(foo)
from t1
where b = 2
....
Questo lo farà.
SELECT A_COUNT as Type ,COUNT(FOO) FROM T1 WHERE T1.A=1,
Union
SELECT B_COUNT as Type, COUNT(FOO) FROM T1 WHERE T1.B=2
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow