需要SQL Server查询帮助 - 存档过去2年内未见的项目

时间:2016-09-02 08:21:26

标签: sql sql-server-2008

我目前正在为以下场景编写SQL查询。

一件设备可以随着时间的推移进行检查,我希望将系统中过去2年内未检查过的任何物品归档。

我有这个时间:

debug-toolbar

我知道我的外部申请将获得在过去2年内检查过的所有物品,但我不确定在外部申请之后在where子句中放入什么以获取在最后一次内未检查的任何物品两年不在外部申请结果。

2 个答案:

答案 0 :(得分:1)

尝试使用以下查询。假设Time_Of_Inspectiondataetime字段

DECLARE @TwoYearsAgo DATETIME;
SET @TwoYearsAgo = DATEADD(year, -2, GETDATE());

SELECT A.Equipment_Label, A.Inspection_ID
FROM Inspections A
WHERE NOT EXISTS
        (
            SELECT 1
            FROM Inspections B
            INNER JOIN Equipment E ON B.Equipment_Label = E.Equipment_Label
            WHERE Time_Of_Inspection BETWEEN @TwoYearsAgo AND GETDATE() AND E.Archived = 0
            AND A.Inspection_ID=B.Inspection_ID
        ) 

答案 1 :(得分:0)

检查在2年前举行,过去2年没有检查过,而且Equipment.Archived = 0。

DECLARE @TwoYearsAgo DATETIME;
SET @TwoYearsAgo = DATEADD(year, -2, GETDATE());

SELECT I.Equipment_Label, I.Inspection_ID
FROM Inspections I
WHERE i.Time_Of_Inspection < @TwoYearsAgo
    AND NOT EXISTS (
    SELECT 1
    FROM Inspections i2
    INNER JOIN Equipment ON i2.Equipment_Label = Equipment.Equipment_Label 
      AND i2.Equipment_Label = I.Equipment_Label
      AND i2.Time_Of_Inspection BETWEEN @TwoYearsAgo AND GETDATE() 
      AND Equipment.Archived = 0
    )