I'm trying to fetch the best-selling SQL product within a certain time period. For this, I have the table 'product_address', which has the following columns:
id (PK) | account_id (FK) | product_id (FK) | precoFinal | created_at | updated_at
Well, I obviously have the produto
table and the contas
table.
Before I had done a SQL that can get the best selling product using a 'count', descending order and limiting the result to the best seller, as follows:
SELECT nome, urlImagem
FROM produtos
WHERE id = (
SELECT produto_id
FROM conta_produtos
GROUP BY produto_id
ORDER BY count(*) DESC
LIMIT 1
);
But now I want to limit this SQL to a certain period, ie, to find out which was the best-selling product in a given date range.
So I think I have to change the SELECT from within. I changed it, tried to elaborate a reasoning, but unfortunately the SQL has some error and I can not see what it is. My SQL:
SELECT produto_id
FROM conta_produtos
GROUP BY produto_id
ORDER BY count(*) DESC
WHERE updated_at BETWEEN '2017-03-03' AND '2017-03-08'
What I realized was that if I put the last line (the main line of my sql, because it does the date filter), SQL does not work. Will this group by id get the most recent date between two equal IDs? Is this what's upsetting my where?
Thank you!