带有CASE条件和SUM()的SELECT查询

43

我目前正在使用这些SQL语句。我的表格有一个名为CPaymentType的字段,其中包含“现金”或“支票”。我可以通过执行2个SQL语句来总结付款金额,如下所示。在这种情况下,当执行2个SQL语句或只执行1个时,用户甚至不会注意到速度差异,但是我不喜欢我的方式,我只想要1个SQL语句。如何使用CASE条件将它们重构为1个语句?我无法弄清楚,因为在线示例的结果要么是1或0或布尔值。我不想包括预日期支票付款。非常感谢。

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType='Cash' and CStatus='Active';

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType='Check' and CDate<=SYSDATETIME() and CStatus='Active';

如果您不想在结果中出现过期支票,那么您的第二个查询似乎可以实现这一点。您对它有什么不喜欢的地方吗? - Dan Bracuk
1
是的,我已经实现了我想要的。但是,我不喜欢使用两个 SQL 语句。我希望这两个语句能够合并为一个带有 CASE 条件的语句 :) - chris_techno25
顺便说一下:“case expression”是更正确的术语。(“expression”评估为单个值。) - Paul Maxwell
5个回答

87
Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

感谢您的所有答案,都是正确的,但我会选择这个,因为我正在寻找一个带有CASE语句的示例。我从未使用过CASE语句,这就是为什么我想尝试这个示例的原因。我只是做了两个SQL语句,以便我的观点能够容易地被理解。非常感谢您! - chris_techno25
@chris_techno25 关于this,我建议您作为新用户,阅读Does this amount to inconsistency in the edit review process?Clarification of edit rejection,[meta]讨论。 - Bleeding Fingers
如果我们想要使用CASE语句,请使用正确的语法。感谢@mudassir-hasan让我们的结果正确。 - Saraz

6
select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

干杯 -

5
为使每个和在单独的列中显示:
Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

1
使用“或”
Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

或者是一个“IN”。
Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

1

我认为你不需要一个case语句。你只需要更新你的where子句,并确保括号正确地分组子句。

SELECT Sum(CAMount) as PaymentAmount 
from TableOrderPayment 
where (CStatus = 'Active' AND CPaymentType = 'Cash') 
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())

在我之前发布的答案中,假定CDate<=SYSDATETIME()也适用于现金支付类型。 我认为我将其拆分,因此仅针对支票付款寻找该子句。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接