how to difference of row numbers approach

杀马特。学长 韩版系。学妹 提交于 2019-12-25 01:37:05

问题


i have data like this table

ItemId  Value   Date
1        2      2017-12-18 17:00:00.000
1        2      2017-12-18 17:02:00.000
1        2      2017-12-18 17:04:00.000
1        3      2017-12-18 17:06:00.000
1        3      2017-12-18 17:08:00.000
1        2      2017-12-18 17:10:00.000
1        2      2017-12-18 17:12:00.000
1        2      2017-12-18 17:16:00.000
1        4      2017-12-18 17:14:00.000

i want to output like this in sql server

ItemId     Value   MaxDate
1          2       2017-12-18 17:04:00.000
1          3       2017-12-18 17:08:00.000
1          2       2017-12-18 17:16:00.000
1          4       2017-12-18 17:14:00.000

thanks for your anwsers.


回答1:


You appear to want the last row before value changes, although I'm not sure where value "4" comes from (my best guess is that the last input row should have a "4" and a different timestamp).

If so, you can simply use lead():

select t.*
from (select t.*,
             lead(value) over (partition by itemId order by date) as next_value
      from t
     ) t
where next_value is null or next_value <> value;


来源:https://stackoverflow.com/questions/47887679/how-to-difference-of-row-numbers-approach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!