2009-06-19 17 views
6

Sto provando a selezionare più riepiloghi condizionali in un risultato di una singola tabella in un database basato su DB2.SQL (DB2) Restituisce più conteggi condizionali in una singola query

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... 

Ogni aiuto è apprezzato.

+0

controllare la mia risposta. Sto lasciando un commento perché sembrano inviare avvisi agli utenti di StackOverflow più rapidi. – Eric

risposta

6

Questo conterà 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 
6
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 clausola è opzionale in senso stretto ma può aiutare le prestazioni. Anche "else null" è implicito quando la clausola else viene omessa, così puoi tranquillamente lasciarla fuori anche.

1
select count(foo) 
    from t1 
where a = 1 
union 
select count(foo) 
    from t1 
where b = 2 
.... 
0

Ciò 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 
Problemi correlati