ajax1515
ajax1515

Reputation: 310

MySQL query to get SUM from joined tables

I have two tables named conversions and cc_sessions.

conversions has the following columns:

session_id (int 11)
cpa (int 11)
revenue (int 11)

cc_sessions has the following columns:

call_session_id (int 11)
agent (int 5)

The two tables are related by session_id and call_session_id.

Here's what I'm trying to get from the query:

sum of all cpa associated with an individual agent whenever the cpa > 0 and revenue = 0

So essentially if agent 17 had 20 conversions where there was no revenue but there was a cpa of 10 I should see a row:

agent sum(cpa)
17     200

Here's what I've tried but it is definitely not working right:

SELECT s.agent, SUM(c.cpa)
FROM edu.conversions c JOIN edu.cc_sessions s ON c.session_id = s.call_session_id 
WHERE c.revenue = '0' AND c.cpa > '0'

Upvotes: 1

Views: 47

Answers (2)

AdamMc331
AdamMc331

Reputation: 16730

If you want to sum something per agent, you'll need to group by agents. Your conditions can stay in there where clause.

Try this:

SELECT s.agent, SUM(c.cpa)
FROM conversion c JOIN cc_sessions s ON s.call_session_id = c.session_id
WHERE c.revenue = 0 AND c.cpa > 0
GROUP BY s.agent;

Here is an SQL Fiddle example.

Upvotes: 1

programmer43229
programmer43229

Reputation: 386

I cannot test this in MySql. This is how it would work in SQL:

SELECT s.agent, SUM(c.cpa)
FROM edu.conversions c
JOIN edu.cc_sessions s ON c.session_id = s.call_session_id
WHERE c.revenue = '0'
AND c.cpa > '0'
GROUP BY s.agent

Since your columns are INT's, perhaps this works better:

SELECT s.agent, SUM(c.cpa)
FROM edu.conversions c
JOIN edu.cc_sessions s ON c.session_id = s.call_session_id
WHERE c.revenue = 0
AND c.cpa > 0
GROUP BY s.agent

Upvotes: 1

Related Questions