[英]Is it possible to use 'case' with and in 'count'?
Is it possible to use case
with and in count
是否可以使用
case
并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()
. 您可以将其与
count()
。 I prefer sum()
: 我更喜欢
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. 您的代码的问题不是
count()
与sum()
而是两种不同case
语法的混合。 When you use case <var> when <val>
, you cannot include any other conditions. 在
case <var> when <val>
使用case <var> when <val>
,不能包含任何其他条件。 Just use when
with the full conditions that you want. 只需
when
具有所需的全部条件when
使用。
And, if you like, you can use count()
instead of sum()
. 而且,如果您愿意,可以使用
count()
代替sum()
。
And, for conciseness, I prefer the month()
function: 而且,为简洁起见,我更喜欢
month()
函数:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.