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.
SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.
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.
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) .
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.
You can use:
Select count(created_date) as counted_leads, created_date as count_date from table group by created_date
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With