Search code examples
sqlisqlquery

SQL SUM function


I tried the following query but it doesn't give the answer that I need

SELECT fname, SUM(salary) FROM employee

I need to have the all the fname records and the Sum value as the next column.

What I get from this query is only the first fname Record and the total summation of the salaries.(only the 1st fname value)


Solution

  • You need to add GROUP BY

    SELECT fname, SUM(salary) 
    FROM employee
    GROUP BY fname
    

    Most RDBMSs would reject your original query as invalid.

    Or in response to the comment to get the SUM from the whole table as an additional column if the OVER clause is supported you can use

    SELECT fname, SUM(salary) OVER ()
    FROM employee
    

    And if it isn't you can use a non correlated sub query.

    SELECT fname, (SELECT SUM(salary) FROM employee)
    FROM employee