根据多个字段的结果/ ID计算最终结果

时间:2017-06-21 20:35:30

标签: sql sql-server sql-server-2012 window subquery

为此扩展解决方案:Calculate Final outcome based on Results/ID

使用相同的业务逻辑,我如何根据LA字段和基于Final Result字段的Employment字段获取另一个+----------+-----------+-----------------+-----------------+ | PersonID | Date | Employment | LA | +----------+-----------+-----------------+-----------------+ | 1 | 2/28/2017 | Stayed the same | Improved | | 1 | 4/21/2017 | Stayed the same | Stayed the same | | 1 | 5/18/2017 | Stayed the same | Improved | | 2 | 3/7/2017 | Improved | Stayed the same | | 2 | 4/1/2017 | Stayed the same | Stayed the same | | 2 | 6/1/2017 | Stayed the same | Improved | | 3 | 3/28/2016 | Improved | Improved | | 3 | 5/4/2016 | Improved | Improved | | 3 | 4/19/2017 | Worsened | Worsened | | 4 | 5/19/2016 | Worsened | Stayed the same | | 4 | 2/16/2017 | Improved | Stayed the same | +----------+-----------+-----------------+-----------------+ ?当涉及多个字段时,排名功能显然会有所不同。

表T1扩展:

+----------+-----------------+-----------------+
| PersonID |  Final Result   | Final Result 2  |
+----------+-----------------+-----------------+
|        1 | Stayed the same | Improved        |
|        2 | Improved        | Improved        |
|        3 | Worsened        | Worsened        |
|        4 | Improved        | Stayed the same |
+----------+-----------------+-----------------+

期望输出:

$array = [["year" => "234","amount" => "2387"],["year" => "23","amount" => "324"]];
/* 
   Depending on PHP Version you can pass additional parameters
   in json_encode for example json_encode($array,JSON_PRETTY_PRINT) 
*/
$string = json_encode($array);
echo $string;

1 个答案:

答案 0 :(得分:1)

添加另一个RN应该工作

select t1.personid, t1.employment, t2.LA
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
left join
    (select t1.PersonID, t1.LA,
                row_number() over (partition by personid
                                order by (case when LA <> 'Stayed the same' then 1 else 2 end),
                                            date desc
                                ) as seqnum
        from t1) t2 on t2.PersonID = t1.PersonID and t2.seqnum = 1
where t1.seqnum = 1