如何在汇总函数中使用订单依据

时间:2019-06-01 04:46:59

标签: sql

我的sql表如下所示

ID  AccountName Credit Debit CurrentBalance
1   John         10     0     10
2   Smith        20     0     20
3   Angel        0      10    20
4   John         30     0     40
5   Smith        0      10    10
6   Angel        30     0     50

预期结果

AccountName TotalCredit TotalDebit CurrentBalance
John        40          0          40
Smith       20          10         10
Angel       30          10         50

我想要每个帐户的贷方和借方之和,以及每个帐户的最新经常余额。

我已使用此查询

select AccountName, 
       SUM(CreditAmount) As CreditAmount, 
       SUM(DebitAmount) As DebitAmount, 
       MAX(CurrentBalance) As CurrentBalance 
from TransactionInfo 
GROUP BY AccountName;

3 个答案:

答案 0 :(得分:1)

如果您的数据库支持constant,则这是一种实现方法:

codeValue

答案 1 :(得分:0)

如果您想按聚合函数排序输出记录,只需编写ORDER BY [查询中的列索引],例如在查询中,如果要按AccountName排序输出,则可以使用ORDER BY 1 [AccountName],ORDER BY 2 [SUM(CreditAmount)],ORDER BY 3 SUM(DebitAmount)等...

答案 2 :(得分:0)

您可以试试这个-

注意::考虑到用户的MAX(ID)将是最新的。

SELECT AccountName, 
SUM(CreditAmount) As CreditAmount, 
SUM(DebitAmount) As DebitAmount, 
(   SELECT CurrentBalance 
    FROM TransactionInfo B 
    WHERE B.AccountName = A.AccountName
    AND B.ID = (SELECT MAX(C.ID) FROM TransactionInfo C WHERE C.AccountName = A.AccountName)
) AS CurrentBalance
FROM TransactionInfo A GROUP BY AccountName;