各个研讨会的报名顺序

时间:2019-04-01 09:58:20

标签: sql oracle

如何使用SQL从车间到车间的输入顺序解决问题。给定一个在车间按顺序执行的操作表(无论如何)。需要在第三列中获取结果。

+---------+----------+----------+
| № order | WorkShop | Sequence |
+---------+----------+----------+
| 1       | 02       | 1        |
+---------+----------+----------+
| 2       | 02       | 1        |
+---------+----------+----------+
| 3       | 01       | 1        |
+---------+----------+----------+
| 4       | 01       | 1        |
+---------+----------+----------+
| 5       | 03       | 1        |
+---------+----------+----------+
| 6       | 01       | 2        |
+---------+----------+----------+
| 7       | 01       | 2        |
+---------+----------+----------+
| 8       | 04       | 1        |
+---------+----------+----------+
| 9       | 01       | 3        |
+---------+----------+----------+
| 10      | 01       | 3        |
+---------+----------+----------+

3 个答案:

答案 0 :(得分:0)

这是空白和岛屿的变体。您可以将当前值与上一行中的值进行比较。然后按车间对这个值变化的时间求和:

select t.*,
       sum(case when prev_workshop = workshop then 0 else 1 end) over (partition by workshop order by num_order
from (select t.*,
             lag(workshop) over (order by num_order) as prev_workshop
      from t
     ) t

答案 1 :(得分:0)

with opwc (num, ws) AS (             -- обычный
       Select 1 num, '02' ws from dual
       union all
       Select 2 , '02' from dual
       union all
       Select 3 , '01'  from dual
       union all
       Select 4 , '01'  from dual
       union all
       Select 5 , '03'  from dual
       union all
       Select 6 , '01'  from dual
       union all
       Select 7 , '01'  from dual
       union all
       Select 8 , '04'  from dual
       union all
       Select 9 , '01'  from dual 
       union all
       Select 10 , '01'  from dual         
  )
  Select num, ws, DENSE_RANK() OVER (PARTITION BY ws ORDER BY numgroup) Seq
 from (Select num, ws, case when lag(ws, 1,1) over (order by num) = ws then num-1 else num end numgroup
  from opwc) o
  order by num

答案 2 :(得分:0)

Gordon Linoff Decision很棒。

select t.num_order, t.workshop, 
   sum(case when prev_workshop = workshop then 0 else 1 end) over (partition by workshop order by num_order) res
from (select t.*,
         lag(workshop) over (order by num_order) as prev_workshop
  from (
       Select 1 num_order, '02' workshop from dual
       union all
       Select 2 , '02' from dual
       union all
       Select 3 , '01'  from dual
       union all
       Select 4 , '01'  from dual
       union all
       Select 5 , '03'  from dual
       union all
       Select 6 , '01'  from dual
       union all
       Select 7 , '01'  from dual
       union all
       Select 8 , '04'  from dual
       union all
       Select 9 , '01'  from dual 
       union all
       Select 10 , '01'  from dual         
  ) t
 ) t
order by num_order