Example :
We have one advertisement slot in our website and we want to count number of clicks the advertisement banner has received. Here as the visitor click the ad we will record the ip address, referrer and date of click. Each click will insert all these data and also the current date in date field. For our further analysis we can keep two more fields tack_id and camp_id. We will not discuss more on all these details and focus on SQL part only. The structure of the table with some sample records can be downloaded at the end of this tutorial. To get the number of clicks for each day we will use like this .
SELECTCOUNT(dt) AS no, dt FROM`click_track`GROUPBY dt
We can add order by command to display records starting from highest day ( or current date ) to back by using ORDER BY clause. Here it is
SELECTCOUNT(dt) AS no, dt FROM`click_track`GROUPBY dt ORDERBY dt DESC
If you have a datetime field where along with date, time is also stored then applying group by command will not return total records of the day. We can't use group by command like above. The group by command has to be applied for Year , month and day part. Like this
SELECTCOUNT( dt ) AS no, dt FROM`click_track`GROUPBYDATE(dt)
If we want only year wise data then like this.
SELECTYEAR(dt) AS year_no, COUNT(*) AS no FROM dt_tb GROUPBYYEAR(dt)
Now for day wise
SELECTDAY(dt) AS day_no, COUNT(*) AS no FROM dt_tb GROUPBYDAY(dt)
Why not month also
SELECTMONTH(dt) AS month_no, COUNT(*) AS no FROM dt_tb GROUPBYMONTH(dt)
Try yourself
If you have a login system where different users login to your discussion forum or to a member area of your site then list out numbers of login in last fifteen days.
After verification of your login details, store a record in your click track system with date, userid and ip address. Then apply group by command and list out number of logins for day.
Total Logins at different Hours of the day
If you are storing date and time in a column ( timestamp ) then you can generate report based on number of logins in different hours of the day.
SELECTHOUR(tm) AS hour_no, COUNT(event_id) AS events FROM dt_table_tm GROUPBYHOUR(tm) ORDERBY hour_no
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.