带有 CASE 条件和 SUM() 的 SELECT 查询
Posted
技术标签:
【中文标题】带有 CASE 条件和 SUM() 的 SELECT 查询【英文标题】:SELECT query with CASE condition and SUM() 【发布时间】:2014-01-22 23:44:19 【问题描述】:我目前正在使用这些 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';
【问题讨论】:
如果您不想在结果中显示过时的支票,您的第二个查询似乎可以实现这一点。你不喜欢它的什么? 是的,我已经实现了我想要的。但是,我不喜欢使用 2 条 sql 语句。我希望将这 2 个合并为 1 个具有 CASE 条件的语句:) 顺便说一句:“案例表达式”是更正确的术语。 (“表达式”的计算结果为单个值。) 【参考方案1】:select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType
干杯-
【讨论】:
【参考方案2】: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';
【讨论】:
感谢您的所有回答,一切都是正确的,但我会选择这个 1,因为我正在寻找带有 CASE 语句的东西。我从未使用过 CASE 语句,这就是我想尝试这个示例的原因。我刚刚做了 2 条 sql 语句,所以我的观点很容易理解。谢谢楼主! @chris_techno25 关于this我建议,既然你是新用户,你可以通过Does this amount to inconsistency in the edit review process?和Clarification of edit rejection,Meta Stack Overflow讨论。 如果我们想使用 CASE 语句,请更正一个。感谢您使我们的结果正确@mudassir-hasan【参考方案3】:我认为您不需要案例陈述。你只需要更新你的 where 子句并确保你有正确的括号来对子句进行分组。
SELECT Sum(CAMount) as PaymentAmount
from TableOrderPayment
where (CStatus = 'Active' AND CPaymentType = 'Cash')
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())
我之前发布的答案假设 CDate
【讨论】:
【参考方案4】:要在单独的列中获取每个总和:
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';
【讨论】:
【参考方案5】:使用“或”
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" & "'"
【讨论】:
以上是关于带有 CASE 条件和 SUM() 的 SELECT 查询的主要内容,如果未能解决你的问题,请参考以下文章