SQL Server:顶级条款条件检查

时间:2017-06-23 10:20:51

标签: sql sql-server

数据:

 UserId     EffectiveDate               Plan  
    162     2015-07-01 00:00:00.000     LT60
    162     2015-10-16 00:00:00.000     LT60
    162     2016-05-02 00:00:00.000     LT60
    15      2015-07-01 00:00:00.000     LT120
    15      2016-06-01 00:00:00.000     LT50

问题:

案例1:如果计划发生变化:选择最新一行

示例:对于用户ID 15计划从LT120,Lt50进行更改,因此将选择LT50行

案例2:如果计划没有改变:选择最早的行

示例:对于用户ID 162,计划与LT60相同,因此应选择第一行2015-07-01

我尝试使用Top 1功能,但如果计划更改则会失败。

2 个答案:

答案 0 :(得分:1)

每次发生变化时,您似乎基本上都想要第一行。基本思路是:

select t.*
from (select t.*,
             min(t.plan) over (partition by t.userid) as min_plan,
             max(t.plan) over (partition by t.userid) as max_plan,
             row_number() over (partition by t.userid order by t.effectivedate) as seqnum_asc,
             row_number() over (partition by t.userid order by t.effectivedate desc) as seqnum_desc
      from t
     ) t
where (min_plan = max_plan and seqnum_asc = 1) or
      (min_plan <> max_plan and seqnum_desc = 1);

答案 1 :(得分:0)

您可以尝试使用count和row_number,如下所示:

Select UserId, EffectiveDate, [Plan] from (
    Select *, RowNum = Row_number() over(partition by userid order by EffectiveDate),
        CntPlan = count([plan]) over(partition by userid, [Plan]),
        CntUser = count([Plan]) over(partition by userid),
        RowNumPlan = Row_number() over(partition by userid order by effectiveDate desc)
        from #Plan
) a
where ( a.CntPlan = a.CntUser and rownum = 1)
    or (a.CntPlan <> a.CntUser and RowNumPlan = 1)