比较多行日期的最佳方法

时间:2018-05-10 20:29:31

标签: sql-server tsql

假设下表......

func NewFooIterator(app *App, batchSize int) *Iterator {
    return &Iterator{
        hasNext:   true,
        batchSize: batchSize,
        more: func(offset int, batchSize int) (int, interface{}) {
            batch := it.app.GetAllFoosInPages(offset, it.batchSize)
            return len(batch), batch
        },
    }
}

fooIterator := NewFooIterator(a, 100)

for fooIterator.HasNext() {
    fooBatch := fooIterator.Next().([]*model.Foo)
    // Do stuff
}

如果每行之间的DATEDIFF小于90天,我想为每个CREATE TABLE Dummy_Data ( ID INT, TextField VARCHAR(20), DateField DATE ) INSERT INTO Dummy_Data (ID, TextField, DateField) VALUES (1, 'Random Text', '2018-01-04'), (1, 'Random Text', '2018-02-04'), (1, 'Random Text', '2018-05-01'), (2, 'Random Text', '2017-01-14'), (2, 'Random Text', '2017-05-01'), (2, 'Random Text', '2018-01-01'), (2, 'Random Text', '2018-02-01'), (3, 'Random Text', '2018-01-04') 返回MAX(DateField)

如果DATEDIFF在每行之间的时间超过90天,我想为每个分组返回ID

示例:

因此从上面的第1行到第3行我们知道每行之间的天数DATEDIFF小于90,所以我只想返回:

MAX(DateField)

但是:第4行到第7行的DATEDIFF大于90天,所以我想返回:

ID   TextField      DateField
-------------------------------
1 -  Random Text    2018-05-01

感谢能够解决这一困境的任何人。

1 个答案:

答案 0 :(得分:2)

RexTester DEMO(使用express 2014)希望在2012年有效。

支持Lead(),CTE和DateDiff,所以我想不出为什么不会...

WITH CTE AS (
  SELECT ID
       , textField
       , DateField
       , case when datediff(dd,datefield, lead(datefield) over (partition by ID order by DateField ASC)) > 90 
                OR lead(datefield) over (partition by ID order by DateField ASC) is null then 1 
         else 0 end bInclude
  FROM  Dummy_Data)

SELECT ID, textFIeld, DateField, binclude
FROM CTE
WHERE bInclude = 1;

我们使用LEAD()来查看ID的下一个日期字段。如果为null或者如果> 90天我们用1记录该记录;否则它是0然后我们只包括1。

给我们:

+----+----+-------------+---------------------+----------+
|    | ID |  textFIeld  |      DateField      | binclude |
+----+----+-------------+---------------------+----------+
|  1 |  1 | Random Text | 01.05.2018 00:00:00 |        1 |
|  2 |  2 | Random Text | 14.01.2017 00:00:00 |        1 |
|  3 |  2 | Random Text | 01.05.2017 00:00:00 |        1 |
|  4 |  2 | Random Text | 01.02.2018 00:00:00 |        1 |
|  5 |  3 | Random Text | 04.01.2018 00:00:00 |        1 |
+----+----+-------------+---------------------+----------+