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)
 Duplicating date ranges for each instance

Author  Topic 

tking1
Starting Member

22 Posts

Posted - 2010-12-01 : 17:00:01
Hi,

I have two tables, Table A has user data including a transaction date, Table B has a set of dates within a date range (say 1/1/10-1/31/10).

I need to put these together in such a way that ALL dates within the date range in Table B are given for EACH user in Table A. If there are user transactions for any of the dates in the range, that data will be populated in additional columns based on the contents of Table A.

(Ex.)
user1 1/1/10 transID
user1 1/2/10
user1 1/3/10 transID
.
.
.
user1 1/31/10
user2 1/1/10
user2 1/2/10 transID
user2 1/3/10
.
.
.
user2 1/31/10 transID

and so on...options?


malpashaa
Constraint Violating Yak Guru

264 Posts

Posted - 2010-12-01 : 19:23:26
Try something like this:

DECLARE @TableA TABLE
(
user_name VARCHAR(10) NOT NULL,
transaction_date DATETIME NOT NULL,
transaction_id INT NOT NULL,
PRIMARY KEY(user_name, transaction_date)
);

INSERT INTO @TableA(user_name, transaction_date, transaction_id)
VALUES('User1', '20100101', 1),
('User1', '20100103', 2),
('User2', '20100102', 1),
('User2', '20100131', 1);

DECLARE @TableB TABLE
(
date DATETIME NOT NULL PRIMARY KEY
);

INSERT INTO @TableB(date)
SELECT DATEADD(DAY, V.number, '20100101')
FROM master..spt_values AS V
WHERE V.type = 'P'
AND V.number BETWEEN 0 AND 30;

SELECT A1.user_name,
B.date,
A2.transaction_id
FROM (SELECT DISTINCT user_name
FROM @TableA) AS A1
CROSS JOIN
@TableB AS B
LEFT OUTER JOIN
@TableA AS A2
ON A2.user_name = A1.user_name
AND A2.transaction_date >= B.date
AND A2.transaction_date < DATEADD(DAY, 1, B.date);
Go to Top of Page

tking1
Starting Member

22 Posts

Posted - 2010-12-02 : 10:06:19
Ok, I'll try that. Thanks for your help.
Go to Top of Page
   

- Advertisement -