Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Count for each date

Tags:

sql

tsql

I have the following need

I have a logging table which logs som leads generated each day.

Now I need to pull a report over the amount of leads for each day over the last 10 days.

Lets say the table looks like this:

tbl_leads id int, first_name nvarchar(100), last_name nvarchar(100), created_date datetime 

And I need to count the number of leads for each day, 10 days total. SO the result set should look something like this:

counted_leads | count_date 5             | 2009-04-30 7             | 2009-04-29 5             | 2009-04-28 7             | 2009-04-27 

... and so on

Anyone know how to do this the best possible way? My current solution is iterating with a foreach in c# but I would very much like to hand it on the sql server instead in a sp.

like image 415
The real napster Avatar asked Apr 30 '09 19:04

The real napster


People also ask

How do I count a specific date in SQL?

SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.

How do I count between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How do I count the number of orders in SQL?

The first step is to use the GROUP BY clause to create the groups (in our example, we group by the country column). Then, in the ORDER BY clause, you use the aggregate function COUNT, which counts the number of values in the column of your choice; in our example, we count distinct IDs with COUNT(id) .

How does count (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


2 Answers

You can use:

Select      count(created_date) as counted_leads,      created_date as count_date from      table group by      created_date 
like image 118
Fabio Vinicius Binder Avatar answered Oct 02 '22 17:10

Fabio Vinicius Binder


Your created_date field is datetime, so you'll need to strip off the time before the grouping will work if you want to go by date:

SELECT COUNT(created_date), created_date  FROM table  WHERE DATEDIFF(created_date, getdate()) < 10 GROUP BY convert(varchar, created_date, 101) 
like image 20
Dave Swersky Avatar answered Oct 02 '22 17:10

Dave Swersky