问题描述
您可以使用的差异来识别组row_numbers()
。连续值将具有一个常数。
select col1, col2, date1, min(date2), max(date2), rate
from (select t.*,
(row_number() over (partition by col1, col2, date1 order by date2) -
row_number() over (partition by col1, col2, date1, rate order by date2)
) as grp
from table t
) t
group by col1, col2, date1, rate, grp
解决方法
考虑一些表T
,按Col1,Col2,Date1,Date2
以下顺序排序:
Col1 Col2 Date1 Date2 rate
ABC 123 11/4/2014 11/5/2014 -90
ABC 123 11/4/2014 11/6/2014 -55
ABC 123 11/4/2014 11/7/2014 -90
ABC 123 11/4/2014 11/10/2014 -90
我想对数据进行分组,以便轻松审核/减少重复,所以我有
Col1 Col2 Date1 start_Date2 end_Date2 rate
ABC 123 11/4/2014 11/5/2014 11/5/2014 -90
ABC 123 11/4/2014 11/6/2014 11/6/2014 -55
ABC 123 11/4/2014 11/7/2014 11/10/2014 -90
如果我可以得到另一列,行编号为1 2 3 3
(仅重要的是数字是不同的),然后再创建GROUP BY
该列,则可以轻松做到这一点。
我在查询中的尝试:
SELECT *,DENSE_RANK() OVER (ORDER BY rate) island
FROM T
ORDER BY Date2
没有给出我想要的东西:
Col1 Col2 Date1 Date2 rate island
ABC 123 11/4/2014 11/5/2014 -90 1
ABC 123 11/4/2014 11/6/2014 -55 2
ABC 123 11/4/2014 11/7/2014 -90 1
ABC 123 11/4/2014 11/10/2014 -90 1
我希望查询能够识别出第二组-90
值,因为它们出现在具有不同的组之后,因此应将其视为新组rate
。
[gaps-and-islands] SQL标记非常有用,但是当速率恢复到先前的值时,我还无法弄清楚如何处理。我应该如何修改查询?