带有SUM的CASE语句

时间:2016-03-29 07:36:55

标签: mysql case case-statement

这是我的表结构。

===================================
main_section | currency | amount
===================================

Tender           INR        2000
Bank             USD        3000
Tender           INR        1500
Tender           INR        1850
===================================

我试图做一个CASE陈述,其中如果' main_section =招标'它应该返还投标金额,如果它的银行应该返还银行金额。如果有多个记录,那么它应该总和并返回金额(此处招标有多个记录)。谁能帮我这个。以下是我试过的案例陈述

CASE sum(com_payments.main_section 
         WHEN com_payments.main_section = 'Tender' 
         THEN main_tender = com_payments.amount
END AS maintender1)
CASE sum(com_payments.main_section 
         WHEN com_payments.main_section = 'Bank' 
         THEN main_bank = com_payments.amount
END AS mainbank1)

1 个答案:

答案 0 :(得分:5)

您必须执行条件聚合

SELECT SUM(CASE WHEN main_section = 'Tender' THEN amount END) AS maintender1,
       SUM(CASE WHEN main_section = 'Bank' THEN amount END) AS mainbank1      
FROM mytable