I have two tables in my database as below:
categories table:
Column Name | Column Type |
---|---|
ID | INT |
Name | TEXT |
IDParent | DOUBLE |
and advertisements table:
Column Name | Column Type |
---|---|
ID | INT |
IDUser | INT |
DateAdded | DATETIME |
IDCategory | INT |
Price | DOUBLE |
I have a task in my project as below:
The user ID of the user who has the most ads in the period of one month (thirty days) in the real estate consultant category (including Estate) for each advertiser.
my code is:
SELECT IDUser
FROM (
SELECT a1.IDUser,
COUNT(a2.ID) AS AdCount
FROM advertisements a1
INNER JOIN advertisements a2 ON a1.IDUser = a2.IDUser
INNER JOIN categories c ON a2.IDCategory = c.ID
WHERE c.Name LIKE '%Estate%'
AND a2.DateAdded BETWEEN a1.DateAdded AND DATE_ADD(a1.DateAdded, INTERVAL 30 DAY)
GROUP BY a1.IDUser, a1.DateAdded
) AS Sub
GROUP BY IDUser
ORDER BY MAX(AdCount) DESC
LIMIT 1;
my code problem:
I think my code has a problem: it doesn’t calculate for All thirty days
and
I also want to override the code and use window functions
can you help me to do this?
3
Answers
You can use below query,
The above is the query that I have solved on a sample dataset using the window function. If my approach is wrong, please suggest what went wrong.
SELECT IDUser, COUNT(*) AS Ad_Count
FROM advertisements
WHERE IDCategory IN (SELECT ID FROM categories WHERE Name LIKE ‘%Estate%’)
AND DateAdded >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
GROUP BY IDUser
ORDER BY Ad_Count DESC
LIMIT 1;
Demo: https://dbfiddle.uk/Ai_ZhJMg