MySql SUM 和 JOIN
我正在尝试计算销售代理列表的销售额,该计数每隔几分钟进行一次,并更新显示“销售排行榜”的屏幕,该屏幕是在后台使用 Ajax 调用进行更新的。
我有一个每晚创建并填充的表,其中包含 agent_id 以及一周和一个月的总销售额。我创建了第二个临时表,用于计算当天的销售额。
我需要合并这两个表来创建 agent_count 中所有代理的当前销售列表。
表agent_count;
agent_id (varchar),
team_id (varchar),
name (varchar),
day(int),
week(int),
month(int)
餐桌销售;
agent_id (varchar),
day(int)
我不知道如何组合这些表。我认为我需要使用联接,因为必须返回所有代理 - 即使它们没有出现在 agent_count 表中。
首先,我进行一个简单的调用来获取所有代理的周和月总计,
SELECT agent_id, team_id, name, week, month FROM agent_count;
然后创建一个今天销售额的临时表,然后计算每个代理当天的销售额
CREATE TEMPORARY TABLE temp_todays_sales
SELECT s.id, s.agent_id
FROM sales s
WHERE DATEDIFF(s.uploaded, NOW()) = 0
AND s.valid = 1;
SELECT tts.agent_id, COUNT(tts.id) as today
FROM temp_todays_sales tts
GROUP BY tts.agent_id;
将这些结合起来结束的最佳/最简单的方法是什么提供一个结果集,例如
agent_id, team_id, name, day, week, month
周和月还包括每日总计,
感谢您的帮助!
克里斯蒂
I am trying to count sales made by a list of sales agents, this count is made every few minutes and updates a screen showing a 'sales leader board' which is updates using a Ajax call in the background.
I have one table which is created and populated every night containing the agent_id and the total sales for the week and month. I create a second, temporary table, on the fly which counts the sales for the day.
I need to combine the two tables to create a current list of sales for all agents in agent_count.
Table agent_count;
agent_id (varchar),
team_id (varchar),
name (varchar),
day(int),
week(int),
month(int)
Table sales;
agent_id (varchar),
day(int)
I can't figure out how to combine these tables. I think I need to use a join as all agents must be returned - even if they don't appear in the agent_count table.
First I make a simple call to get the week and month totals for all agents
SELECT agent_id, team_id, name, week, month FROM agent_count;
the I create a temporary table of todays sales, and then I count the sales for each agent for the day
CREATE TEMPORARY TABLE temp_todays_sales
SELECT s.id, s.agent_id
FROM sales s
WHERE DATEDIFF(s.uploaded, NOW()) = 0
AND s.valid = 1;
SELECT tts.agent_id, COUNT(tts.id) as today
FROM temp_todays_sales tts
GROUP BY tts.agent_id;
What is the best/easiet way to combine these to end up with a resultset such as
agent_id, team_id, name, day, week, month
where week and month also include the daily totals
thanks for any help!
Christy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
agent_count
中没有代理的记录,team_id
和name
将为NULL
。如果两个表中都缺少代理,您通常需要进行 FULL JOIN ,但由于
MySQL
不支持后者,您可以使用它的穷人替代:team_id
andname
will beNULL
if there is no record inagent_count
for an agent.If the agents can be missing from both tables, you normally would need to make a
FULL JOIN
but sinceMySQL
does not support the latter you may use its poor man's substitution: