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 2008 Forums
 Transact-SQL (2008)
 select null from each day with in a date span

Author  Topic 

jgonzalez14
Yak Posting Veteran

73 Posts

Posted - 2011-08-08 : 12:41:10
Hi,

I am trying to check if there was a blood drive for a given center on each day of the week with in a time span. My query is doing this just when there actually is a drive. I would like the query to return a null value for the opid if there was not a drive on that given day and not skip the days where there are no drives for that given blood drive.

the #Nums table is a table with a column called N and its values are 1 - 10000. This table allows me to loop through all days within the given time span.

thanks for any help



declare @startDate as DATETIME, @endDate as DATETIME;
set @startDate = dateadd(yyyy,-5,getdate());
set @endDate = dateadd(yyyy,-4,getdate());

select
b.bloodbanksitename,
o.opid,
convert(varchar , DATEADD(day, #Nums.n - 1, @startDate), 101) AS thedate

from
#Nums
left join
op as o on convert(varchar, DATEADD(day, #Nums.n - 1, @startDate), 112) = convert(varchar, o.opStartDateTime, 112)
left join
bloodbanksite AS b ON b.bloodbanksiteid = o.bloodbanksiteid
WHERE
#Nums.n <= DATEDIFF(day, convert(varchar, @startDate, 112), convert(varchar, @endDate, 112)) + 1

order by
b.bloodbanksitename,
thedate

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-08 : 13:36:54
you need a calendar table to which you join yourtable and check if there's any drive for that day
.

see link below to understand how to generate a calendar table

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

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

Go to Top of Page

jgonzalez14
Yak Posting Veteran

73 Posts

Posted - 2011-08-08 : 14:33:16
How would I use that with the following query?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-09 : 10:00:43
do a cross join with your #Nums table and use

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

Go to Top of Page
   

- Advertisement -