根据 Results/ID 计算最终结果
Calculate Final outcome based on Results/ID
对于 Table 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 |
+----------+-----------+-----------------+
我正在尝试根据相对于先前结果的最新 result/person 在 Employment/PersonID 字段上计算 Final Result
字段分区。 Final Result
:
背后的逻辑解释了我的意思
对于每个人,
如果所有results/person都保持不变,那么只应该final
该人的结果是 "Stayed the same"
如果Worsened/Improved
在一个人的结果集中,最终结果应该是
该人的最新 Worsened/Improved 结果,与 W/I 结果之后的 "Stayed the same" 无关。
例如:
- 第 1 个人最终结果 -> 与 (1) 相同
- 第 2 个人最终结果 -> 根据 (2)
进行了改进
- 人 3 最终结果 -> 根据 (2)
恶化
- 第 4 个人最终结果 -> 根据 (2)
进行了改进
想要的结果:
+----------+-----------------+
| PersonID | Final Result |
+----------+-----------------+
| 1 | Stayed the same |
| 2 | Improved |
| 3 | Worsened |
| 4 | Improved |
+----------+-----------------+
我知道这可能涉及 Window 函数或子查询,但我正在努力编写代码。
嗯。这是一个优先查询。这听起来像 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;
对于 Table 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 |
+----------+-----------+-----------------+
我正在尝试根据相对于先前结果的最新 result/person 在 Employment/PersonID 字段上计算 Final Result
字段分区。 Final Result
:
对于每个人,
如果所有results/person都保持不变,那么只应该final 该人的结果是 "Stayed the same"
如果Worsened/Improved 在一个人的结果集中,最终结果应该是 该人的最新 Worsened/Improved 结果,与 W/I 结果之后的 "Stayed the same" 无关。
例如:
- 第 1 个人最终结果 -> 与 (1) 相同
- 第 2 个人最终结果 -> 根据 (2) 进行了改进
- 人 3 最终结果 -> 根据 (2) 恶化
- 第 4 个人最终结果 -> 根据 (2) 进行了改进
想要的结果:
+----------+-----------------+
| PersonID | Final Result |
+----------+-----------------+
| 1 | Stayed the same |
| 2 | Improved |
| 3 | Worsened |
| 4 | Improved |
+----------+-----------------+
我知道这可能涉及 Window 函数或子查询,但我正在努力编写代码。
嗯。这是一个优先查询。这听起来像 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;