SQL:一种比较结果集中没有自连接的行的方法

时间:2013-10-01 07:00:52

标签: sql sql-server self-join

有没有办法比较没有自连接的表的2行?

我有一个包含列的事件表:ID,日期,工具。我查询它,并在结果集中添加行号(按日期排序,分别为每个工具)。现在我想知道第1行和第4行之间的时差是否超过一周 我可以通过将我的查询加入到自身(非常简单)来实现这一点,但它会使查询运行两次(对吗?)这不是非常有效(因为我的查询不简单并且已经需要一些加入)。有没有更聪明的方法来实现这个目标?

我正在使用SQL服务器(不确定哪个版本;可能是2008年),并从ASP.NET应用程序查询,因此我没有对数据库的管理访问权限,而且一些高级内容不起作用(但我'我愿意尝试每一个建议和检查)。 感谢。

1 个答案:

答案 0 :(得分:0)

你可以使用窗口函数来实现你的目标,但也许结束(分区依据... 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