SQL中的列总数

时间:2018-10-09 05:28:00

标签: sql

我的表中有2列DebitCredit。我在做Debit - Credit

如果Debit - Credit的总和> = 0,则在“借方贷方贷方”中添加值。

现在如何在特定列中添加值?

我正在使用此查询

SELECT
    ActName,
    CASE WHEN SUM(DebitAmount - CreditAmount) >= 0 THEN 'DebitAmount'
         WHEN SUM(DebitAmount - CreditAmount) <= 0 THEN 'CreditAmount' END
FROM 
    TblAWSLocalTrans
GROUP BY
    ActName
ORDER BY
    ...

3 个答案:

答案 0 :(得分:2)

您的语法略有偏离。如果我理解正确,则希望汇总帐户中的贷方/借方,然后在适当时报告贷方或借方。如果帐户有贷方,则应在借方上显示0,反之亦然。如果帐户有贷方,则相反。

SELECT
    ActName,
    CASE WHEN SUM(CreditAmount - DebitAmount) >= 0
         THEN SUM(CreditAmount - DebitAmount)
         ELSE 0 END AS TotalCreditAmount,
    CASE WHEN SUM(DebitAmount - CreditAmount) > 0
         THEN SUM(DebitAmount - CreditAmount)
         ELSE 0 END AS TotalDebitAmount
FROM TblAWSLocalTrans
GROUP BY ActName
ORDER BY ActName;

Demo

答案 1 :(得分:0)

我认为您的查询将如下所示

SELECT
    ActName,
    CASE WHEN SUM(DebitAmount - CreditAmount) >= 0
    THEN  SUM(DebitAmount+CreditAmount)
    else  SUM(DebitAmount - CreditAmount)  END
FROM TblAWSLocalTrans
GROUP BY ActName

答案 2 :(得分:0)

我认为您的查询有误。按照此

SELECT
    ActName,
    CASE WHEN SUM(DebitAmount - CreditAmount) >= 0
    THEN  SUM(DebitAmount+CreditAmount)
    else  SUM(DebitAmount - CreditAmount)  END
FROM TblAWSLocalTrans
GROUP BY ActName