SQL 交叉联接仅限于彼此相隔 7 天内的日期

SQL cross join restricted to dates within 7 days of each other

我想进行交叉联接,但只保留彼此相隔 7 天内的记录对。我下面的代码保留了日期完全相同的对。如何修改以允许日期在 7 天内?我正在使用 SQL Server 2008。

SELECT 
t1.[id] AS [A_id],
t2.[id] AS [B_id],
t1.[date] AS [A_date],
t2.[date] AS [B_date],
t1.[item] AS [A_item],
t2.[item] AS [B_item],
INTO [records_crossed]
FROM [records] t1
CROSS JOIN [records] t2
WHERE 
t1.[date]=t2.[date]
ORDER BY t1.[id],t2.[id]

你如何表达这样的连接并不重要。查询本质上是:

SELECT . . .
INTO [records_crossed]
FROM [records] t1 JOIN
     [records] t2
     ON ABS(DATEDIFF(DAY, t1.[date], t2.[date])) <= 7
ORDER BY t1.[id], t2.[id];

这将生成重复的倒置(相同的两条记录以不同的顺序)和相同的记录。如果您不想要这样的记录:

SELECT . . .
INTO [records_crossed]
FROM [records] t1 JOIN
     [records] t2
     ON DATEDIFF(DAY, t1.[date], t2.[date]) BETWEEN 0 AND 7 AND
        t1.id <> t2.id
ORDER BY t1.[id], t2.[id];

这将提供您所需要的,并允许在 [records].[date] 上使用索引(如果存在)。

SELECT 
    t1.[id] AS [A_id],
    t2.[id] AS [B_id],
    t1.[date] AS [A_date],
    t2.[date] AS [B_date],
    t1.[item] AS [A_item],
    t2.[item] AS [B_item],
INTO 
    [records_crossed]
FROM 
    [records] t1
    INNER JOIN [records] t2 ON
        t2.[date] BETWEEN DATEADD(DAY,-7,t1.[date]) AND DATEADD(DAY,+7,t1.[date])
ORDER BY 
    t1.[id],
    t2.[id];