I am building a query where I need to join three tables.
Here are my tables
agents(id, full_name)
agent_orders(id, agent_id, [..])
agent_targets(id, agent_id, month_target, amount)
The month_target
in agent_orders
is a DATE
field, I am interested only in the month and year portion, but I added the day for convenience.
Here is my query
SELECT
agents.full_name,
COUNT(DISTINCT orders.id) total_orders,
COUNT(DISTINCT yearly_targets.id) nr_yearly_targets,
SUM(yearly_targets.amount) yearly_target,
month_target.amount monthly_target
FROM agent_targets yearly_targets
LEFT JOIN agents ON yearly_targets.agent_id = agents.id AND YEAR(yearly_targets.month) = YEAR(CURRENT_DATE())
LEFT JOIN agent_targets month_target ON month_target.agent_id = agents.id AND MONTH(month_target.month) = MONTH(CURRENT_DATE()) AND YEAR(month_target.month) = YEAR(CURRENT_DATE())
LEFT JOIN agent_orders orders ON orders.agent_id = agents.id
GROUP BY agents.id
The problem is that yearly_target
is not the right amount. Every other data is correct. I tried a couple of things and the problem occurs when I join the orders table
. If I don't join the orders table, the data is correct.
How can I solve this ? The yearly_target
is always a huge number that does not rappresents the correct value.
Thank you