SQL交叉连接仅限于7天内的日期

时间:2016-02-01 13:30:19

标签: sql sql-server sql-server-2008 date dateinterval

我想进行交叉连接,但只保留彼此在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]

2 个答案:

答案 0 :(得分:1)

如何表达这种联接并不重要。查询基本上是:

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];

答案 1 :(得分:0)

这将提供您所需的内容,并允许在[records].[date]上使用INDEX。

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];