使用分区按查询对值进行分组

时间:2018-04-19 16:31:31

标签: sql oracle

我正在研究oracle和以下格式的数据,

样本表和数据......

create table testd
(
  Source_id varchar2(20),
  job_status varchar2(20)
);

insert into testd testd values('ABC', 'canceled');
insert into testd testd values('ABC', 'failed');
insert into testd testd values('ABC', 'finished');
insert into testd testd values('DEF', 'canceled');
insert into testd testd values('DEF', 'failed');
insert into testd testd values('DEF', 'finished');
insert into testd testd values('DEF', 'canceled');
insert into testd testd values('DEF', 'failed');
insert into testd testd values('DEF', 'finished');
insert into testd testd values('DEF', 'canceled');
insert into testd testd values('PQR', 'failed');
insert into testd testd values('PQR', 'finished');

======================

我将列分组为

Source_id   job_status  Count
ABC         canceled    1
ABC         failed      1
ABC         finished    1
DEF         canceled    3
DEF         failed      2
DEF         finished    2
PQR         failed      1
PQR         finished    1

尝试使用此查询,但无法实现所需的输出。

  select Source_id, job_status,
  count(job_status) over (partition by Source_id order by Source_id desc)  as r
  from testd

我的预期输出是前2个source_ids,有作业状态计数,请参见下面的示例。

e.g。

Source_id   job_status  Count
DEF         canceled    3
DEF         failed      2
DEF         finished    2
ABC         canceled    1
ABC         failed      1
ABC         finished    1

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您需要删除ORDER BY

select DISTINCT Source_id, job_status,
   count(job_status) over (partition by Source_id, job_status)  as r
from testd;

或简单地说:

SELECT Source_id, job_status, COUNT(*)
FROM testd
GROUP BY Source_Id, job_status;

<强> DBFiddle Demo

答案 1 :(得分:0)

我在下面尝试过,任何其他解决方案都会非常感激。

select source_id, job_status, count(*)
from testd
where Source_Id in ( select source_id from 
                                  (
                                      SELECT source_id, COUNT(job_status) Res 
                                      from testd
                                      group by source_id
                                      order by res desc
                                  )  
                                  where rownum <= 2
               )
group by  source_id, job_status
order by source_id