Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - Using SUM with JOIN

Tags:

join

mysql

sum

Ok, so I have 4 tables.

A users table with columns id and name.

A groups table with columns id, name and owner.

A items table with columns group and content.

A content table with columns id, name and duration.

Each user can have several groups. Each group can have several items inside it. Each item represents one of the pieces of content.

I want to be able to list all the groups, with a sum of all durations of each piece of content inside that group.

What Ive been trying is this:

select groups.id,groups.name,users.name,sum(content.duration) as duration from groups
join users on groups.owner=users.id
join items on items.group=groups.id
join content on content.id=items.content

Unfortunately this only gives me one result, with a total sum of all the durations of each piece of content in all of the groups - like so:

"g001", "Group 1", "Me", "400"

What I am expecting is something like:

"g001", "Group 1", "Me", "160"
"g002", "Group 2", "You", "160"
"g003", "Group 3", "Them", "80"
like image 758
Jimmery Avatar asked Feb 08 '13 13:02

Jimmery


People also ask

How do I sum a group in MySQL?

SUM() function with group by MySQL SUM() function retrieves the sum value of an expression which has undergone a grouping operation by GROUP BY clause.

How can I sum two columns in MySQL?

MySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .

Can we use sum with where clause?

In SQL, we use the SUM() function to add the numeric values in a column. It is an aggregate function in SQL. The aggregate function is used in conjunction with the WHERE clause to extract more information from the data.


2 Answers

try this

   select groups.id,groups.name,users.name,sum(content.duration) as duration from groups
   join users on groups.owner=users.id
   join items on items.group=groups.id
   join content on content.id=items.content
   group by groups.name
like image 118
echo_Me Avatar answered Oct 12 '22 02:10

echo_Me


Try this:

select groups.id,groups.name,users.name,sum(content.duration) as duration
from groups
    join users
        on groups.owner=users.id
    join items
        on items.group=groups.id
    join content
        on content.id=items.content
group by groups.id,groups.name,users.name
like image 35
Hamlet Hakobyan Avatar answered Oct 12 '22 02:10

Hamlet Hakobyan