sqloracle-databaseora-00937

Show sum of all for every record


Say you have table of some items with these two columns:

....where ItemName is unique.

How do you show sum of all prices for every ItemName (I'm using Oracle)? If I just try this:

SELECT ItemName, 
       SUM(Price)
  FROM Items

I get this error:

ORA-00937: not a single-group group function

...which goes away only if I use GROUP BY. But then I can SUM only by groups, not all of them.


Solution

  • You can't both group and not group in the same query. You can use a subquery to get the price:

    select ItemName, (select sum(Price) from Items) as AllPrices
    from Items
    

    As the subquery doesn't use any data from the records in the main query, the database should be able to optimise it to only execute the subquery once.