SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 tsql query to get the data each day of the range
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

sqlservernovice
Starting Member

9 Posts

Posted - 12/11/2012 :  16:24:11  Show Profile  Reply with Quote
Declare @date1= '01-01-2012'
Select a.ID, a.locID, @date1 AS OperatingDate
from dataset A
where A.startDate <= @date1
AND (A.endDate >= @date1 or a.endDate is null)
AND A.condition <> 1

the data looks like this when execution of this query
id locID OperatingDate

716 30411 1-1-2011
828 10615 1-1-2011
.
.
some 100 records


But when given a range i want to get the data in the following format
id locID OperatingDate
7165 30411 1-2-2011
8284 10615 1-2-2011
.
.
some 100 records
7165 30411 1-3-2011
8284 10615 1-3-2011
.
.
some 92 records
7165 30411 1-4-2011
8284 10615 1-4-2011
.
.
some 99 records

How can i achieve it,not sure what would be the best option to use a while or cursor or a CTE

sunitabeck
Flowing Fount of Yak Knowledge

5155 Posts

Posted - 12/11/2012 :  17:21:47  Show Profile  Reply with Quote
Do you mean something like this?
DECLARE @date1 DATETIME = '20120101'
DECLARE @date2 DATETIME = '20120430';
SELECT a.ID,
       a.locID,
       @date1 AS OperatingDate
FROM   dataset A
WHERE  A.startDate >= @date1
       AND (A.endDate <= @date2 OR a.endDate IS NULL)
       AND A.condition <> 1
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 12/14/2012 :  02:03:32  Show Profile  Reply with Quote
till how many months you've to repeat this?

DECLARE @date1 DATETIME = '20120101'
DECLARE @date2 DATETIME = '20120430';

;With Months (N)
AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM Months
WHERE DATEADD(mm,N+1,@date1) <=@date2
)
SELECT a.ID,
       a.locID,
       DATEADD(mm,N,@date1) AS OperatingDate
FROM   dataset A
CROSS JOIN Months m
WHERE  A.startDate >= @date1
       AND (A.endDate <= @date1 OR a.endDate IS NULL)
       AND A.condition <> 1


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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000