如何按X天筛选SQL查询日期结果

时间:2018-08-06 14:21:12

标签: sql sql-server sql-server-2008

如何使用与旧日期相差3天的E_date过滤结果。

如果E_date超过3天,则需要跳过数据。

我的脚本:

DECLARE @Date_From DATE
DECLARE @Date_To DATE

SET @Date_From = '2018-04-01'
SET @Date_To = '2018-04-30'

SELECT * 
FROM
    (SELECT 
         Ref, E_Date, Item, Customer,
         COUNT(*) OVER (PARTITION BY Customer, Item) AS cnt
     FROM 
         Events
     WHERE 
         E_Date BETWEEN @Date_From AND DATEADD(DAY, 1, @Date_To)) t 
WHERE 
    cnt > 1 
ORDER BY  
    Item, Customer;

结果:

+------+-------------+-----------+------+
|  Ref |  E_Date     |  Customer | Item |
+------+-------------+-----------+------+
|  101 | 15-Apr-2018 | ABC       | HP   |
|  102 | 26-Apr-2018 | ABC       | HP   |
|  103 | 28-Apr-2018 | ABC       | HP   |
|  104 | 30-Apr-2018 | ABC       | HP   |
|  105 | 1-Apr-2018  | EEE       | DELL |
|  106 | 5-Apr-2018  | EEE       | DELL |
|  107 | 12-Apr-2018 | EEE       | DELL |
|  108 | 14-Apr-2018 | EEE       | DELL |
+------+-------------+-----------+------+

预期结果:

+------+-------------+-----------+------+
|  Ref |  E_Date     |  Customer | Item |
+------+-------------+-----------+------+
|  102 | 26-Apr-2018 | ABC       | HP   |
|  103 | 28-Apr-2018 | ABC       | HP   |
|  104 | 30-Apr-2018 | ABC       | HP   |
|  107 | 12-Apr-2018 | EEE       | DELL |
|  108 | 14-Apr-2018 | EEE       | DELL |
+------+-------------+-----------+------+

1 个答案:

答案 0 :(得分:1)

使用带有Datediff和线索功能的外部查询

DECLARE @Date_From DATE
DECLARE @Date_To DATE

SET @Date_From = '2018-04-01'
SET @Date_To = '2018-04-30'

SELECT Ref
    ,E_Date
    ,Customer
    ,Item
FROM (
    SELECT *
        ,DATEDIFF(dd, E_Date, LEAD(E_Date) OVER (
                PARTITION BY customer order by item
                )) Date_Diff
    FROM (
        SELECT Ref
            ,E_Date
            ,Item
            ,Customer
            ,COUNT(*) OVER (
                PARTITION BY Customer
                ,Item
                ) AS cnt
        FROM Events
        WHERE E_Date BETWEEN @Date_From AND DATEADD(DAY, 1, @Date_To)
        ) t
    WHERE cnt > 1
    ) x
WHERE Date_Diff <= 3 OR Date_diff IS NULL
ORDER BY Item
    ,Customer;

从您的样本数据中得出的结果

Ref E_Date    Customer  Item
102 2018-04-26  ABC     HP
103 2018-04-28  ABC     HP
104 2018-04-30  ABC     HP
107 2018-04-12  EEE     DELL
108 2018-04-14  EEE     DELL