简体   繁体   English

MySQL查询从联接表中获取SUM

[英]MySQL query to get SUM from joined tables

I have two tables named conversions and cc_sessions . 我有两个表,名为conversionscc_sessions

conversions has the following columns: conversions包含以下几列:

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

cc_sessions has the following columns: cc_sessions包含以下列:

call_session_id (int 11)
agent (int 5)

The two tables are related by session_id and call_session_id . 这两个表通过session_idcall_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 每当cpa > 0revenue = 0时,与单个agent相关联的所有cpa总和

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: 因此,从本质上讲,如果代理17进行了20次转化,没有任何收入,但每次转化费用为10,我应该看到一行:

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'

I cannot test this in MySql. 我无法在MySql中对此进行测试。 This is how it would work in SQL: 这就是它在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: 由于您的列是INT ,所以这可能会更好:

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

If you want to sum something per agent, you'll need to group by agents. 如果要对每个业务代表进行汇总,则需要按业务代表分组。 Your conditions can stay in there where clause. 您的条件可以留在where子句中。

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. 这是一个SQL Fiddle示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM