简体   繁体   中英

SQL Cursor - Count Each Occurrence in Group

Been out of the SQL world for a minute and need to know how I can change the below code to count each occurrence where code = 0 in each group where the id is the same and then proceed to the next group of id's.

Basically, I need a count of how many orders with the same id have more than one occurrence of code being 0.

Sample Data:

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

My goal would give me a count of "1" for the above sample data.

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;

You can do this with a simple query. No need for a loop:

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

If you want to print the value out in a PL/SQL block:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM