SQL Sum Multiple rows into one

前端 未结 5 2071
有刺的猬
有刺的猬 2021-01-04 03:51

I need some help with the SUM feature. I am trying to SUM the bill amounts for the same account into one grand total, but the results I am getting show my SUM column just m

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 04:32

    If you don't want to group your result, use a window function.

    You didn't state your DBMS, but this is ANSI SQL:

    SELECT AccountNumber, 
           Bill, 
           BillDate, 
           SUM(Bill) over (partition by accountNumber) as account_total
    FROM Table1
    order by AccountNumber, BillDate;
    

    Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1

    You can even add a running sum, by adding:

    sum(bill) over (partition by account_number order by bill_date) as sum_to_date
    

    which will give you the total up to the current's row date.

提交回复
热议问题