SQL按日期范围划分

时间:2018-07-30 12:28:17

标签: sql sql-server tsql

假设这是我的桌子:

ID  NUMBER  DATE
------------------------
1   45      2018-01-01
2   45      2018-01-02
2   45      2018-01-27

我需要使用partition by和row_number分开,其中一个日期与另一个日期之间的差异大于5天。上面的示例将导致这样的结果:

ROWNUMBER   ID  NUMBER  DATE
-----------------------------
1           1   45      2018-01-01
2           2   45      2018-01-02
1           3   45      2018-01-27

我的实际查询是这样的:

SELECT ROW_NUMBER() OVER(PARTITION BY NUMBER ODER BY ID DESC) AS ROWNUMBER, ...

但是您会注意到,它不适用于日期。我该如何实现?

3 个答案:

答案 0 :(得分:4)

您可以使用lag函数:

select *, row_number() over (partition by number, grp order by id) as [ROWNUMBER]
from (select *, (case when datediff(day, lag(date,1,date) over (partition by number order by id), date) <= 1 
                      then 1 else 2 
                 end) as grp
      from table
     ) t;

答案 1 :(得分:1)

通过使用lagdatediff功能

select * from
    (
    select t.*,
           datediff(day,
                    lag(DATE) over (partition by NUMBER order by id),
                    DATE
                   ) as diff
    from  t 
      ) as TT where  diff>5

http://sqlfiddle.com/#!18/130ae/11

答案 2 :(得分:1)

我认为您想使用POST models/<X>/dbBABYLON.SceneLoader.ImportMesh("", "./public/Models/", "model1.stl", scene, function (newMeshes) { // Set the target of the camera to the first imported mesh camera.target = newMeshes[0]; a = newMeshes[0]; }); BABYLON.SceneLoader.ImportMesh("", "./public/Models/", "model2.stl", scene, function (newMeshes) { // Set the target of the camera to the first imported mesh //camera.target = newMeshes[0]; b = newMeshes[0]; }); var aCSG = BABYLON.CSG.FromMesh(a); var bCSG = BABYLON.CSG.FromMesh(b); 以及一个累加的总和来标识然后使用lag()

datediff()