SQL 光标 - 计算组中的每次出现次数
SQL Cursor - Count Each Occurrence in Group
离开 SQL 世界一分钟,需要知道如何更改下面的代码以计算每个 ID 相同的组中代码 = 0 的每次出现次数,然后继续下一组id。
基本上,我需要计算具有相同 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;
您可以通过简单的查询来完成此操作。不需要循环:
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;
离开 SQL 世界一分钟,需要知道如何更改下面的代码以计算每个 ID 相同的组中代码 = 0 的每次出现次数,然后继续下一组id。
基本上,我需要计算具有相同 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;
您可以通过简单的查询来完成此操作。不需要循环:
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;