--===== Create a test table. -- This is NOT part of the solution. IF OBJECT_ID('TempDB..#YourTable') IS NOT NULL DROP TABLE #YourTable CREATE TABLE #YourTable( AccountNbr INT, CreateDate DATETIME)--===== Populate the test table with data. -- This is NOT part of the solution. INSERT INTO #YourTable (AccountNbr,CreateDate) SELECT '59961','01/05/09' UNION ALL SELECT '59961','01/06/09' UNION ALL SELECT '59961','01/07/09' UNION ALL SELECT '32187','01/05/09' UNION ALL SELECT '32187','01/06/09' UNION ALL SELECT '22195','01/10/09' UNION ALL SELECT '22195','01/12/09' UNION ALL SELECT '22195','01/13/09' UNION ALL SELECT '22195','01/15/09' UNION ALL SELECT '69248','01/11/09' UNION ALL SELECT '69248','01/12/09'--===== You might be tempted to use this, but it contains a -- triangular join and will slow down in a hurry if you -- have more than just a handful of rows for each AccountNbr. -- I posted this to warn you that it's bad. SELECT AccountNbr, CreateDate, Seq = (SELECT COUNT(*) FROM #yourtable i WHERE i.AccountNbr = o.AccountNbr AND i.CreateDate <= o.CreateDate) FROM #yourtable o ORDER BY o.AccountNbr, o.CreateDate--===== Instead, use the following method which will solve a -- million rows in about 7 seconds. IF OBJECT_ID('TempDB..#SeqWork') IS NOT NULL DROP TABLE #SeqWorkDECLARE @PrevAccountNbr INT,-- @PrevCreateDate DATETIME, @PrevSeq INT SELECT ISNULL(AccountNbr,0) AS AccountNbr, ISNULL(CreateDate,0) AS CreateDate, CAST(0 AS INT) AS Seq INTO #SeqWork FROM #yourtable ORDER BY AccountNbr, CreateDate ALTER TABLE #SeqWork ADD PRIMARY KEY CLUSTERED (AccountNbr, CreateDate) UPDATE #SeqWork SET @PrevSeq = Seq = CASE WHEN AccountNbr = @PrevAccountNbr THEN @PrevSeq+1 ELSE 1 END, @PrevAccountNbr = AccountNbr FROM #SeqWork WITH(INDEX(0),TABLOCKX) SELECT * FROM #SeqWork ORDER BY AccountNbr, CreateDate
Create Table dbo.SeqNum(AccountNbr Int,CreateDate DateTime)GoInsert Into dbo.SeqNumSelect 59961, '01/05/2009' Union AllSelect 59961, '01/06/2009' Union AllSelect 59961, '01/07/2009' Union AllSelect 32187, '01/05/2009' Union AllSelect 32187, '01/06/2009' Union AllSelect 22195, '01/10/2009' Union AllSelect 22195, '01/12/2009' Union AllSelect 22195, '01/13/2009' Union AllSelect 22195, '01/15/2009' Union AllSelect 69248, '01/11/2009' Union AllSelect 69248, '01/12/2009'GoSelect ( Select Count(AccountNbr) As Seq From dbo.SeqNum B Where A.CreateDate >= B.CreateDate And A.AccountNbr = B.AccountNbr )As SeqNo , A.AccountNbr , A.CreateDateFrom dbo.SeqNum AGoDrop Table dbo.SeqNumGo