I have two tables user_profile
and tracked_search
. The user_profile
table has user details and tracked_search
tracks searches made by each user.
Whenever a user makes a search this search entry goes in the tracked_search
table. If nothing is searched for a particular date nothing is added in tracked_search
.
I need to develop a report where in I need to show on all days of month how many users made searches.
For example:
CREATE TABLE tracked_search (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
created DATE,
user_id int NOT NULL
);
INSERT INTO tracked_search(created, user_id) VALUES
('2017-10-01', 1000),
('2017-10-01', 1000),
('2017-10-01', 2000),
('2017-10-01', 3000),
('2017-10-01', 4000),
('2017-10-04', 1000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 3000),
('2017-10-31', 1000),
('2017-10-31', 2000),
('2017-10-31', 3000),
('2017-10-31', 4000),
('2017-10-31', 5000);
Desired output:
Date user_count
2017-10-01 4
2017-10-02 0
2017-10-03 0
2017-10-04 3
2017-10-05 0
...
2017-10-30 0
2017-10-31 5
I have written following query
SELECT ts.created , count( distinct ts.user_id) FROM tracked_search ts, user_profile u
WHERE ts.created>=(CURDATE()-INTERVAL 1 MONTH) AND u.id = ts.user_id
group by ts.created;
but i get
Date user_count
2017-10-01 4
2017-10-04 3
2017-10-31 5
I need to print all days values if no entry is there for a particular date it should be zero.
I am using MySQL.
See Question&Answers more detail:
os