简体   繁体   中英

Is it possible to use 'case' with and in 'count'?

Is it possible to use case with and in count

 SELECT branches.NAME AS agence, 
       count( 
       CASE loanstatus 
              WHEN '1' 
              AND    Datepart(month,loanaccount.issuedate)= 2 THEN 1 
              ELSE NULL 
       END )AS nombre_de_credits_demande , 
       count( 
       CASE loanstatus 
              WHEN '2' datepart(month,loanaccount.chargeoffdate)= 2 THEN 1 
              ELSE NULL 
       END )AS nombre_de_credits_approuve

please help me

You can use it with count() . I prefer sum() :

select Branches.Name as Agence,
       sum(case when LoanStatus = '1' and
                     datepart(MONTH, LoanAccount.IssueDate) = 2
                then 1 else 0
           end ) as Nombre_de_Crédits_Demandé ,
       sum(case when LoanStatus = '2' and
                     datepart(MONTH, LoanAccount.IssueDate) = 2
                then 1 else 0
           end ) as Nombre_de_Crédits_Approuvé

The issue with your code was not the count() versus sum() it is the mixing of two different case syntaxes. When you use case <var> when <val> , you cannot include any other conditions. Just use when with the full conditions that you want.

And, if you like, you can use count() instead of sum() .

And, for conciseness, I prefer the month() function:

select Branches.Name as Agence,
       sum(case when LoanStatus = '1' and MONTH(LoanAccount.IssueDate) = 2
                then 1 else 0
           end ) as Nombre_de_Crédits_Demandé ,
       sum(case when LoanStatus = '2' and MONTH(LoanAccount.IssueDate) = 2
                then 1 else 0
           end ) as Nombre_de_Crédits_Approuvé

you can achieve your goal through this query.

select
branches.name as agence
,(select COUNT(1) from <table_name> where loginstatus=1 and Datepart(month,loanaccount.issuedate)= 2) as nombre_de_credits_demande
,(select COUNT(1) from <table_name> where loginstatus=2 and Datepart(month,loanaccount.issuedate)= 2) as AS nombre_de_credits_approuve
from <Table_name>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM