如何选择表中的行,其中id是其他id的第一个grup

时间:2017-07-13 20:13:10

标签: sql oracle

我有一张表new_table

ID       PROC_ID       STAFF_ID
1          558           4141
2          558           601
3          558           556
-------------------------------
4          602           601
5          602           795
-------------------------------
6          634           601
7          634           195
8          634           295
-------------------------------
9          705           601
10         705           788
-------------------------------
11         716           458
12         716           601
...        ...           ...
n          1890          4141

当我可以从new_table中选择proc_id,其中staff_id = 601得到结果。例如

proc_id
602
634
705

其中staff_id是第一个order_by id

2 个答案:

答案 0 :(得分:1)

一种方法使用窗口函数:

select proc_id
from (select t.*, row_number() over (partition by proc_id order by id) as seqnum
      from t
     ) t
where seqnum = 1 and staff_id = 601;

另一种有趣的方法是使用带有having子句的聚合:

select proc_id
from t
group by proc_id
having min(id) = min(case when staff_id = 601 then id end);

答案 1 :(得分:1)

这是带有having子句的标准聚合查询。 having子句中的条件使用first/last函数(如果您不熟悉此聚合函数,请使用Google Oracle文档)。

with
     inputs ( id, proc_id, staff_id ) as (
       select  1,  558, 4141 from dual union all
       select  2,  558,  601 from dual union all
       select  3,  558,  556 from dual union all
       select  4,  602,  601 from dual union all
       select  5,  602,  795 from dual union all
       select  6,  634,  601 from dual union all
       select  7,  634,  195 from dual union all
       select  8,  634,  295 from dual union all
       select  9,  705,  601 from dual union all
       select 10,  705,  788 from dual union all
       select 11,  716,  458 from dual union all
       select 12,  716,  601 from dual union all
       select 99, 1890, 4141 from dual
     )
-- End of simulated data (for testing purposes only, not part of the query).
-- Solution begins BELOW THIS LINE.
select   proc_id
from     inputs
group by proc_id
having   min(staff_id) keep (dense_rank first order by id) = 601
;

PROC_ID
-------
602
634
705
相关问题