2014-01-05 104 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 

乾杯 -