这是我的表结构。

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

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

我试图做一个 CASE 语句,如果'main_section=tender'它应该返回投标金额,如果它的银行应该返回银行金额。如果有多个记录,则应求和并返回金额(此处 Tender 有多个记录)。谁能帮我这个。以下是我尝试过的案例陈述
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)

最佳答案

你必须做条件聚合:

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

关于mysql - 带有 SUM 的 CASE 语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36278200/

10-11 07:36