如何添加累积总和列?

时间:2016-06-19 12:14:57

标签: sql sql-server sql-server-2008 sql-server-express

我使用SqlExpress

以下是我获得附加结果的查询。

SELECT ReceiptId, Date, Amount, Fine, [Transaction]
FROM (
    SELECT ReceiptId, Date, Amount, 'DR' AS [Transaction]
    FROM ReceiptCRDR
    WHERE        (Amount > 0)

    UNION ALL

    SELECT        ReceiptId, Date, Amount, 'CR' AS [Transaction]
    FROM            ReceiptCR
    WHERE        (Amount > 0)

    UNION ALL

    SELECT        strInvoiceNo AS ReceiptId, CONVERT(datetime, dtInvoiceDt, 103) AS Date, floatTotal AS Amount,  'DR' AS [Transaction]
    FROM            tblSellDetails
) AS t
ORDER BY Date

结果

enter image description here

想要一个显示余额的新列。 例如。 1行应显示-2500,第2行应显示-3900,第3行应显示-700,依此类推。

基本上,它需要前一行'帐户列'的数据,并根据交易类型进行计算。

示例结果

enter image description here

1 个答案:

答案 0 :(得分:1)

嗯,看起来像SQL-Server,如果您使用的是2012+,那么请使用SUM() OVER()

SELECT t.*,
       SUM(CASE WHEN t.transactionType = 'DR' 
                THEN t.amount*-1
                ELSE t.amount END) 
           OVER(PARTITION BY t.date ORDER BY t.receiptId,t.TransactionType DESC) as Cumulative_Col
FROM (YourQuery Here) t

SUM时的值CRvalue*-1

DR的值

现在我按日期分组,这意味着每天都会重新计算此列,如果您一直想要它,请将OVER()替换为:

OVER(ORDER BY t.date,t.receiptId,t.TransactionType DESC) as Cumulative_Col

另外,我不明白为什么在同一天,因为在ReceiptId之前计算了相同的DR CR,我已将其添加到订单中但如果那不是你想要的,那就更好地解释逻辑了。