表T1
+----------+-----------+-----------------+
| PersonID | Date | Employment |
+----------+-----------+-----------------+
| 1 | 2/28/2017 | Stayed the same |
| 1 | 4/21/2017 | Stayed the same |
| 1 | 5/18/2017 | Stayed the same |
| 2 | 3/7/2017 | Improved |
| 2 | 4/1/2017 | Stayed the same |
| 2 | 6/1/2017 | Stayed the same |
| 3 | 3/28/2016 | Improved |
| 3 | 5/4/2016 | Improved |
| 3 | 4/19/2017 | Worsened |
| 4 | 5/19/2016 | Worsened |
| 4 | 2/16/2017 | Improved |
+----------+-----------+-----------------+
我尝试根据与先前结果相关的最新结果/人来计算就业/ PersonID字段上的Final Result
字段分区。我的意思在Final Result
背后的逻辑中解释:
对于每个人,
如果所有结果/人都保持不变,那么只有最终结果 这个人的结果是"保持不变"
如果有误/改进 在一个人的结果集中,最终的结果应该是 对于那个人来说最新的更糟糕/改进的结果,无论"保持不变"在W / I结果之后。
例如:
期望的结果:
+----------+-----------------+
| PersonID | Final Result |
+----------+-----------------+
| 1 | Stayed the same |
| 2 | Improved |
| 3 | Worsened |
| 4 | Improved |
+----------+-----------------+
我知道这可能涉及窗口函数或子查询,但我很难对此进行编码。
答案 0 :(得分:1)
嗯。这是优先级查询。这听起来像是row_number()
:
select t1.personid, t1.employment
from (select t1.*,
row_number() over (partition by personid
order by (case when employment <> 'Stayed the same' then 1 else 2 end),
date desc
) as seqnum
from t1
) t1
where seqnum = 1;