这是表格内容。每一行都与事件相关:
Id Style BeginDate BeginEvent EndDate EndEvent**
1 Style-2 1/1/2001 Manufacture 3/1/2001 Colorchange
1 Style-2 3/1/2001 Colorchange 5/1/2001 StyleChange
1 Style-3 5/1/2001 StyleChange 10/1/2001 Sold
需要一个可以提供以下输出的查询:
Id, Previous_Style, New_Style, Change_Date
本质上,我想根据表格中的时间顺序事件找出何时发生样式更改。
谢谢!
答案 0 :(得分:2)
只需使用lag()
并过滤即可。据我所知:
select id, prevStyle, Style, BeginDate
from (select t.*,
lag(style) over (partition by id order by begindate) as prevStyle
from t
) t
where BeginEvent = 'StyleChange';
答案 1 :(得分:1)
看起来你可以使用id和结束/开始日期加入自己。
select t1.id
, t2.style as previousstyle
, t1.style as newstyle
, t1.begindate as changedate
from mytable t1
left join mytable t2 on t2.id = t1.id and t2.enddate = t1.begindate
and t2.style <> t1.style