按团队分组数据

时间:2014-08-01 01:06:20

标签: sql

我有一个状态,用于显示何时将工作从一个团队传递到另一个团队。我需要能够运行一个查询来显示重新分配的工作订单以及来自审计a_workorder表的from和to团队。

   status         persongroup     wonum     eaudittimestamp
1. REASSIGN       TEAM4           324153    30/07/2014 22:15
2. REASSIGN       CARP            324153    30/07/2014 22:15
3. REASSIGN       TEAM1           324145    30/07/2014 22:34
4. REASSIGN       FOODBEV         324145    30/07/2014 22:34

如果对包含CARP的persongroup的所有wonum运行查询,则应返回第1行和第2行,因为TEAM4将工单号324153重新分配给CARP。

1 个答案:

答案 0 :(得分:0)

这是一种不优雅的解决方案(当我使用select distinct时,它总是让我暂停),但它可以为您提供所需的基础:

with ranks as (
  select
    persongroup, wonum, eaudittimestamp,
    min (eaudittimestamp) over (partition by wonum) as min_time,
    max (eaudittimestamp) over (partition by wonum) as max_time
  from a_workorder
), wos as (
  select distinct wonum
  from a_workorder
)
select
  wos.wonum, r1.persongroup as first_group,
  r2.persongroup as last_group
from
  wos
  join ranks r1 on
    wos.wonum = r1.wonum and
    r1.eaudittimestamp = r1.min_time
  join ranks r2 on
    wos.wonum = r2.wonum and
    r2.eaudittimestamp = r2.max_time

您的样本数据的结果:

wonum   first_group   last_group
-----   -----------   ----------
324153  'TEAM4'       'CARP'
324145  'TEAM1'       'FOODBEV'