Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Record Per Day in Select

Author  Topic 

edwardborner
Starting Member

1 Post

Posted - 2010-05-10 : 09:08:57
Hi Guys,

I have a table with the following fields:

* Date
* Value

I need to write a select which returns the count of value per day of a particular month. Where a day contains no records it should be defaulted to 0. So the output would be something like this:

Day Count
----------------
1 123
2 0
3 2345

... And so on until the last day of the month.

I had a suggestion to create a table which stores the days of the month and join on that. But that would suggest that each month had the same number of days.

Any help with this would be greatly appreciated.

Thanks!

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-05-10 : 09:52:49
Try something like this

select day(t1.dates),count(t2.date_col) from
(
select dateadd(day,number,dateadd(month,datediff(month,0,getdate())-1,0)) as dates from master..spt_values
where type='p' and dateadd(day,number,dateadd(month,datediff(month,0,getdate())-1,0))<dateadd(month,datediff(month,0,getdate()),0)
) as t1
left join your_table as t2
on
t2.date_col>=dateadd(month,datediff(month,0,getdate())-1,0) and
t2.date_col<dateadd(month,datediff(month,0,getdate()),0)


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-05-10 : 13:35:11
or this?

http://visakhm.blogspot.com/2010/02/generating-calendar-table.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -