SQL Sum Multiple rows into one

前端 未结 5 2029
有刺的猬
有刺的猬 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:37

    I tried this, but the query won't run telling me my field is invalid in the select statement because it is not contained in either an aggregate function or the GROUP BY clause. It's forcing me to keep it there. Is there a way around this?

    You need to do a self-join. You can't both aggregate and preserve non-aggregated data in the same subquery. E.g.

    select q2.AccountNumber, q2.Bill, q2.BillDate, q1.BillSum
    from
    (
    SELECT AccountNumber, SUM(Bill) as BillSum
    FROM Table1
    GROUP BY AccountNumber
    ) q1,
    (
    select AccountNumber, Bill, BillDate
    from table1
    ) q2
    where q1.AccountNumber = q2.AccountNumber
    

提交回复
热议问题