代码之家  ›  专栏  ›  技术社区  ›  Bluemarble

SQL Server-根据列值跨行更改的方式计算行数

  •  0
  • Bluemarble  · 技术社区  · 6 年前

    待处理员工

    enter image description here

    现在,我需要为每个员工提取第一个(最小)和最后一个(最大)记录ID,并执行以下操作:

    1. 如果第一个记录是美国,最后一个记录是加拿大:则将该员工标记为“美国到加拿大”。
    2. 如果最后一个记录是美国,第一个记录是加拿大:则将该员工标记为“Canada to USA”。

    我的最终目标是制作下表——这张表将显示在这两个国家流动的雇员人数。

    TBL U迁移

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    听起来你想要每个员工的第一行和最后一行。然后您可以跟踪整个移动:

    select first_workfrom, last_workfrom, count(*)
    from (select t.*,
                 first_value(workfrom) over (partition by employee order by recordid) as first_workfrom,
                 first_value(workfrom) over (partition by employee order by recordid desc) as last_workfrom
          from t
         ) t
    group by first_workfrom, last_workfrom
    having first_workfrom <> last_workfrom;
    
        2
  •  0
  •   Yogesh Sharma    6 年前

    第一个值和最后一个值自2012年或更高版本起可用,如果您使用较低版本运行,则可以使用 apply :

    select movement, count(*)
    from (select distinct t.employee, 
                 concat(t1.workfrom, ' to ', t11.workfrom) as movement
          from table t cross apply
               ( select top (1) t1.*
                 from table t1
                 where t1.employee = t.employee 
                 order by t1.id 
               ) t1 cross apply
               ( select top (1) t11.*
                 from table t11
                 where t11.employee = t.employee 
                 order by t11.id desc 
               ) t11
          where t1.workfrom <> t11.workfrom
         ) t
    group by movement;