Domanda

I am working on a million data rows table.The table look likes below

Departement    year Candidate   Spent  Saved 

Electrical     2013   A          50     50
Electrical     2013   B          25     50
Electrical     2013   C          11     50
Electrical     2013   D          25     0
Electrical     2013   Dt          86     50
Electrical     2014   AA         50     50
Electrical     2014   BB         25     0
Electrical     2014   CH         11     50
Electrical     2014   DG         25     0
Electrical     2014   DH         0      50
Computers      2013   Ax         50     50
Computers      2013   Bc         25     50
Computers      2013   Cx         11     50
Computers      2013   Dx         25     0
Computers      2013   Dx         86     50

I am looking output like below.

Departement    year   NoOfCandidates    NoOfCandidatesWith50$save      NoOfCandidatesWith0$save
Electrical     2013      5                    4                              1                       
Electrical     2014      5                    3                              2
Computers      2013      5                    4                              1

I am using #TEMP tables for every count where conditions and left outer joining at last .So it takes me more time. Is there any way so i can perform better for above Table . Thanks in advance.

È stato utile?

Soluzione

You want to do this as a single aggregation query. There is no need for temporary tables:

select department, year, count(*) as NumCandidates,
       sum(case when saved = 50 then 1 else 0 end) as NumCandidatesWith50Save
       sum(case when saved = 0 then 1 else 0 end) as NumCandidatesWith00Save
from table t
group by department, year
order by 1, 2;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top