在过程调用的函数中使用两个 sum() 时,我遇到了一个问题。输入的结果是分开的。以下表格,功能和程序是我尝试过的。PS - 当有一个 sum(x) 时它工作正常。
DROP TABLE MATCH;
CREATE TABLE MATCH
(M_ID VARCHAR2 (4) NOT NULL,
HT_ID VARCHAR2 (4),
AT_ID VARCHAR2 (4),
P_F NUMBER (3),
P_A NUMBER (3));
INSERT INTO MATCH VALUES
('M01','T1', 'T2', 2, 0);
INSERT INTO MATCH VALUES
('M02','T1', 'T2', 1, 1);
INSERT INTO MATCH VALUES
('M03','T1', 'T2', 0, 2);
INSERT INTO MATCH VALUES
('M04','T1', 'T2', 0, 2);
INSERT INTO MATCH VALUES
('M05','T2', 'T1', 2, 0);
INSERT INTO MATCH VALUES
('M06','T2', 'T1', 0, 2);
INSERT INTO MATCH VALUES
('M07','T2', 'T1', 1, 2);
INSERT INTO MATCH VALUES
('M08','T2', 'T1', 0, 2);
临时表(将存储结果):
DROP TABLE RESULTS;
CREATE GLOBAL TEMPORARY TABLE RESULTS
(ht_id varchar2 (5),
FINAL NUMBER (2))
ON COMMIT PRESERVE ROWS;
insert into RESULTS values('T1', NULL);
insert into RESULTS values('T2', NULL);
insert into RESULTS values('T3', NULL);
insert into RESULTS values('T4', NULL);
insert into RESULTS values('T5', NULL);
我申请的查询:
select
sum(case when HT_ID='T1' then P_F else 0 end) +
sum(case when AT_ID='T1' then P_A else 0 end)
from match;
返回 9 的结果,我在一个函数中应用了选择查询,并创建了一个过程来调用该函数并将结果存储在一个临时表中。尽管在函数中完成的求和结果是分开的(例如,T1 为 6,T2 为 3,尽管仅 T1 应该有 9 个点)。
HT_ID FINAL
----- ----------
T1 3
T2 6
T3 0
T4 0
T5 0
如何保留与查询相同的结果并将它们输入到临时表中?如下所示:
HT_ID FINAL
----- ----------
T1 9
T2 0
T3 0
T4 0
T5 0
这是我在功能和程序方面尝试过的:
drop function RESULTSFINAL;
CREATE OR REPLACE FUNCTION RESULTSFINAL(i_HT_ID RESULTS.HT_ID%TYPE)
RETURN VARCHAR2
IS
v_RESULTS_FINAL RESULTS.FINAL%TYPE;
BEGIN
select sum(case when HT_ID='T1' then P_F else 0 end)+ sum(case when AT_ID='T1' then P_A else 0 end)
INTO v_RESULTS_FINAL
FROM MATCH
WHERE HT_ID = i_HT_ID;
IF v_RESULTS_FINAL IS NULL THEN
v_RESULTS_FINAL := 0;
END IF;
RETURN v_RESULTS_FINAL;
END;
/
步骤:
CREATE OR REPLACE PROCEDURE FINALSCORES
AS
CURSOR c_RESULTS
IS
SELECT HT_ID
FROM RESULTS;
v_HT_ID RESULTS.HT_ID%TYPE;
v_RESULTS_FINAL RESULTS.FINAL%TYPE;
BEGIN
OPEN c_RESULTS;
LOOP
FETCH c_RESULTS INTO v_HT_ID;
EXIT WHEN c_RESULTS%NOTFOUND;
v_RESULTS_FINAL := RESULTSFINAL(v_HT_ID);
UPDATE RESULTS
SET FINAL = v_RESULTS_FINAL
WHERE HT_ID = v_HT_ID;
END LOOP;
CLOSE c_RESULTS;
END;
/
执行最终分数;
提前致谢。