SQL游标 - 计算组

时间:2016-04-11 19:20:17

标签: sql oracle cursor fetch

离开SQL世界一分钟,需要知道如何更改下面的代码来计算id为相同的每个组中代码= 0的每次出现,然后继续下一组id&# 39; S

基本上,我需要计算具有相同id的多少订单有多个代码出现的数量为0。

示例数据:

+------+------+
|  ID  | CODE |
+------+------+
| 1234 |    0 |
| 1234 |    1 |
| 1234 |    3 |
| 1234 |    0 |
| 1234 |    2 |
| 5678 |    0 |
| 5678 |    1 |
| 5678 |    2 |
+------+------+

我的目标是给我一个" 1"对于上述样本数据。

Declare
n_id NUMBER;
n_code NUMBER;
N_COUNT NUMBER:=0;

cursor dups is
select id, code 
from process;

BEGIN

OPEN DUPS; 

LOOP

FETCH DUPS INTO N_ID, N_CODE;

EXIT WHEN DUPS%NOTFOUND;

  IF n_code = 0 THEN
    N_COUNT := N_COUNT +1;
  END IF;

END LOOP;

  IF N_COUNT > 1 THEN
   dbms_output.put_line ('Record: ' || n_count);
  END IF;

CLOSE DUPS;

END;

1 个答案:

答案 0 :(得分:2)

您可以通过简单的查询来完成此操作。不需要循环:

select count(*)
from (select id, count(*) as cnt
      from process
      where code = 0
      group by id
     ) p
where cnt > 1;

如果要在PL / SQL块中输出值:

declare
   v_cnt number;
begin
    select count(*)
    into v_cnt
    from (select id, count(*) as cnt
          from process
          where code = 0
          group by id
         ) p
    where cnt > 1;

    dbms_output.put_line(v_cnt);
end;