您可以使用窗口函数来实现您的目标,但也许 over(partition by ... order by) 就足够了(http://www.sqlfiddle.com/#!6/2d448/1
):
IF OBJECT_ID('tempdb..#SomeTable', 'U') IS NOT NULL
BEGIN
DROP TABLE #SomeTable
END
create table #SomeTable (Id int, [date] datetime, tool nvarchar(80), description nvarchar(80))
DECLARE @date AS DATETIME
SET @date = CAST('2013-01-10' as datetime)
declare @i as int = 0
declare @j as int = 0
declare @k as int = 0
WHILE (@i < 100)
begin
set @i = @i + 1
set @j = 0
WHILE (@j < 100)
begin
set @j = @j + 1
set @k = CAST(RAND() * 100 as int)
insert into #SomeTable (Id, [date], tool, description) values (@i*@j, DATEADD(dd,@k,@date), 'tool-' + STUFF('000', 3-LEN(@i)+1, LEN(@i), @i) , 'description-' + CAST(@i as nvarchar(10)) + '-' + CAST(@j as nvarchar(10)))
end
end
--may be this will be enough
--select *, DATEDIFF(dd, MIN([date]) OVER(PARTITION BY tool), [date]) AS 'days' from #SomeTable order by tool, days
--sql 2012 only
--4 rows window
--select *, DATEDIFF(dd, MIN([date]) OVER(PARTITION BY tool ORDER BY tool, [date] ROWS BETWEEN 4 PRECEDING AND CURRENT ROW), [date]) AS 'days' from #SomeTable order by tool, days
select *, DATEDIFF(dd, MIN([date]) OVER(ORDER BY tool, [date] ROWS BETWEEN 4 PRECEDING AND CURRENT ROW), [date]) AS 'days' from #SomeTable order by tool, days