fikir
Programmer
- Jun 25, 2007
- 86
I have this table, with site id, visitstartdate and visitenddate
I am trying to get the sequence of visit, and wrote this query
this workis fine if the site have different visitstartdate, the proble comes if the site has two differnt visits with the same visitdate. In this case I have to consider the visitenddate and visitenddate of lesser date become the first and the later will be the second visit
example for the table
how I could I do that
Thanks
I am trying to get the sequence of visit, and wrote this query
Code:
DECLARE @TBL TABLE (ID INT, VSTARTDATE DATETIME, VENDDATE DATETIME)
INSERT INTO @TBL
SELECT 1, '01/01/2007', '01/10/2007'
UNION ALL SELECT 1, '01/03/2007', '01/15/2007'
UNION ALL SELECT 1, '01/04/2007', '01/16/2007'
UNION ALL SELECT 2, '01/01/2007', '01/15/2007'
SELECT TBL.ID, TBL.VSTARTDATE, 'v' + CONVERT(VARCHAR(10), COUNT(TBL2.VSTARTDATE)) AS VISIT
FROM @TBL TBL LEFT JOIN @TBL TBL2
ON TBL.ID = TBL2.ID
AND DATEPART(QUARTER, TBL.VSTARTDATE) = DATEPART(QUARTER, TBL2.VSTARTDATE)
AND DATEPART(YEAR, TBL.VSTARTDATE) = DATEPART(YEAR, TBL2.VSTARTDATE)
AND TBL.VSTARTDATE >= TBL2.VSTARTDATE
GROUP BY TBL.ID, TBL.VSTARTDATE
ORDER BY TBL.ID
this workis fine if the site have different visitstartdate, the proble comes if the site has two differnt visits with the same visitdate. In this case I have to consider the visitenddate and visitenddate of lesser date become the first and the later will be the second visit
example for the table
Code:
DECLARE @TBL TABLE (ID INT, VSTARTDATE DATETIME, VENDDATE DATETIME)
INSERT INTO @TBL
SELECT 1, '01/01/2007', '01/10/2007'
UNION ALL SELECT 1, '01/03/2007', '01/15/2007'
UNION ALL SELECT 1, '01/03/2007', '01/16/2007'
UNION ALL SELECT 2, '01/01/2007', '01/15/2007'
the output should look like
id visitstartdate visit
1 2007-01-01 v1
1 2007-01-03 v2
1 2007-01-03 v3
2 2007-01-01 v1
how I could I do that
Thanks