插入复杂的有序组计数器

时间:2016-03-24 13:46:20

标签: sql-server sql-insert

我尝试创建一个复杂的SQL-Insert,我不确定在标题中找到正确的流行语。

好的,这里有一些数据可以解决我的问题:

Date      Type
20160321  entry
20160322  entry
20160324  entry
20160325  delete
20160424  entry
20160425  entry
20160428  update
20160504  update
20160520  update
20160520  entry

现在我想按照日期的顺序每次更改“类型”来创建组...以便最后存在以下表格:

Date      Type    Group
20160321  entry   1
20160322  entry   1
20160324  entry   1
20160325  delete  2
20160424  entry   3
20160425  entry   3
20160428  update  4
20160504  update  4
20160520  update  4
20160520  entry   5

我尝试了很多东西......使用LEAD,LAG,FIRST_VALUE以及稍后使用row_number进行更新......但是这个解决方案无效... 我的问题是这些组不能由数据本身定义......这些组在订单和价值组合之前出现......

我希望你能理解我的问题并且能够帮助我!

1 个答案:

答案 0 :(得分:3)

您可以使用以下查询:

SELECT [Date], [Type], 
       DENSE_RANK() OVER (ORDER BY min_Date) AS [Group]
FROM(
  SELECT [Date], [Type],
         MIN([Date]) OVER (PARTITION BY [Type], grp) AS min_Date
  FROM ( 
    SELECT [Date], [Type],
         ROW_NUMBER() OVER (ORDER BY [Date]) - 
         ROW_NUMBER() OVER (PARTITION BY [Type] ORDER BY [Date]) AS grp
    FROM mytable) AS t) AS s
ORDER BY [Date]

<强>解释

最里面的查询:

SELECT [Date], [Type],
       ROW_NUMBER() OVER (ORDER BY [Date]) - 
       ROW_NUMBER() OVER (PARTITION BY [Type] ORDER BY [Date]) AS grp
FROM mytable

检测共享相同Type值的连续记录的 islands

Date        Type    grp
========================
20160321    entry   0
20160322    entry   0
20160324    entry   0
20160325    delete  3
20160424    entry   1
20160425    entry   1
20160428    update  6
20160504    update  6
20160520    update  6
20160520    entry   4

第二级查询使用MIN()OVER()来计算每个Date切片的最小Type值:

Date        Type    min_Date
============================
20160321    entry   20160321
20160322    entry   20160321
20160324    entry   20160321
20160325    delete  20160325
20160424    entry   20160424
20160425    entry   20160424
20160428    update  20160428
20160504    update  20160428
20160520    update  20160428
20160520    entry   20160520

现在可以通过在Group字段上应用DENSE_RANK来轻松计算min_Date值。