2014-01-05 74 views
1

我目前正在使用这些sql语句。我的表的字段CPaymentType包含“Cash”或“Check”。我可以通过执行2条SQL语句来总结付款金额,如下所示。在这种情况下,用户甚至在执行2个sql语句或1个时不会注意到速度差异,但是,我不喜欢我的方式,我只想要1个sql语句。我如何将这些重构成CASE条件的1条语句?我无法弄清楚,因为在线示例导致1或0或布尔值。我不希望包含过期的支票付款。非常感谢你。带CASE条件和SUM的SELECT查询()

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'; 
+0

如果你不想在你的结果期票,你的第二查询似乎实现这一目标。你不喜欢它什么? –

+0

是的,我已经达到了我想要的。但是,我不喜欢使用2个sql语句。我希望将这2个合并到CASE条件下的1条语句中:) –

回答

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'; 
+0

谢谢您所有的答案,所有答案都是正确的,但是我会选择这个1,因为我正在寻找CASE语句的内容。我从来没有使用CASE语句,这就是为什么我想尝试这个例子。我只做了2个sql语句,所以我的观点很容易理解。谢谢你,先生! –

+0

@ chris_techno25关于[this](http://stackoverflow.com/review/suggested-edits/3732435)我建议,因为你是一个新用户,你需要经过[这是否等同于编辑评审过程中的不一致?](http://meta.stackexchange.com/q/182419/221866)和[编辑拒绝的澄清](http://meta.stackexchange.com/q/179655/221866),[meta]讨论。 –

0

使用一个 “或”

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" & "'" 
0

要获得每个总和在单独的列:

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'; 
0

我不你认为你需要一个案例陈述。你只需要更新你的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()也适用于现金付款方式为好。我想我把它分拆出来,所以它只查找支票付款的条款。

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

干杯 -