Ky -
Ky -

Reputation: 32083

How do I summarize rows in an SQL table?

I have a table like:

EMP_NAME HOURS_WORKED
-------- ------------
Jane               10
Jane                2
Jane               18
Jane               12
Alex                7
Alex                3
Alex                5
Danny              20
Danny              16

And I want to condense it into:

EMP_NAME TOTAL_HOURS_WORKED
-------- ------------------
Jane                     42
Alex                     15
Danny                    36

I tried this, but it didn't run:

SELECT
  DISTINCT EMP_NAME,
  SUM(HOURS_WORKED) TOTAL_HOURS_WORKED
  FROM EMPLOYEES
;

As far as I can tell, you can combine columns with +, and you can summarize all rows into one cell using SUM(), but I don't know how to combine rows like this.

I've done my best Google-Fu, but I still can't find anything to help me :/


Please note that this is an example table I made on the spot. I'd never use a name as a primary key ;)

Upvotes: 0

Views: 43

Answers (1)

Raging Bull
Raging Bull

Reputation: 18737

Try this:

SELECT EMP_NAME,
SUM(HOURS_WORKED) TOTAL_HOURS_WORKED
FROM EMPLOYEES
GROUP BY EMP_NAME

Upvotes: 2

Related Questions