简体   繁体   English

无法在MySQL选择查询中使用Case语句?

[英]Unable to use Case statement in Mysql select query?

Here is my query and Grouping by Transaction type C for Credit and D for Debit and 这是我的查询和按交易类型C划分的贷方和D借方的分组和

SELECT 
case 
WHEN ACT.TRANSACTIONTYPE='C' THEN SUM(ACT.AMOUNT) END AS CreditBalance,
case 
WHEN ACT.TRANSACTIONTYPE='D' THEN SUM(ACT.AMOUNT) END AS DebitBalance
FROM accounttransaction ACT 
WHERE ACT.TRANSACTIONTYPE IS NOT NULL
GROUP BY ACT.TRANSACTIONTYPE;

Below is my result 以下是我的结果

CreditBalance DebitBalance
16536          NULL
NULL           9673

Now I want to Subtract the balance of the A/C then I need to show as Current Balance Account transaction table includes Accountnumber,transactiontype and amount 现在我想减去账目余额,然后我需要显示为“当前余额”科目交易表,其中包括“科目号”,“交易类型”和“金额”

You are grouping by TransactionType , so the results show up on different rows. 您正在按TransactionType分组,因此结果显示在不同的行上。 You need to remove the group by and move the condition expressions inside the sum() : 您需要删除group by并在sum() 移动条件表达式:

select sum(case when  ACT.TRANSACTIONTYPE = 'C' then act.amount end) as CreditBalance,
       sum(case when  ACT.TRANSACTIONTYPE = 'D' then act.amount end) as DebitBalance
from AccountTransaction act
WHERE act.TRANSACTIONTYPE IS NOT NULL;

Do you just want the grand total of all the credit / debit amounts? 您是否只想要所有贷方/借方金额的总计?

If so maybe the following:- 如果是这样,可能是以下情况:

SELECT Accountnumber, SUM(CASE WHEN transactiontype = 'C' THEN amount ELSE -1 * amount END) 
FROM accounttransaction
WHERE transactiontype IS NOT NULL
GROUP BY Accountnumber

Or to give the credit and debit amounts separately as well as the overall total 或分别给出贷方和借方金额以及总金额

SELECT Accountnumber, 
    SUM(CASE WHEN transactiontype = 'C' THEN amount ELSE 0 END) AS CreditTotal,
    SUM(CASE WHEN transactiontype = 'D' THEN amount ELSE 0 END) AS DebitTotal,
    SUM(CASE WHEN transactiontype = 'C' THEN amount WHEN transactiontype = 'D' THEN -1 * amount ELSE 0 END) AS OverallTotal
FROM accounttransaction
WHERE transactiontype IS NOT NULL
GROUP BY Accountnumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM