返回另一个对象中列总和的成员函数
Posted
技术标签:
【中文标题】返回另一个对象中列总和的成员函数【英文标题】:Member function to return sum of column in another object 【发布时间】:2016-02-01 21:47:39 【问题描述】:我目前已经在oracle中实现了下面的代码。
我正在努力创建一个返回村庄居民数量的成员函数。
我将如何做这件事并最终创建一个匿名块进行测试,然后最终针对它运行一个 select 语句?
房屋对象
create or replace type house as object (
house_no number,
postcode varchar2(10),
no_of_residents number,
member function pass(h house) return number
);
/
房屋对象主体
create or replace type body houses_p12214840 as
member function pass(h houses_p12214840) return number is
begin
if (h.house_no=house_no) and (h.road_name=road_name)
and (h.postcode=postcode)
and (h.no_of_residents=no_of_residents)
then
return 1;
else
return 0;
end if;
end;
end;
/
村阵式,多户型
create or replace type village_array is varray(50) of house;
/
我的村桌
create table village (
villageid number,
village_name varchar2(25),
village village_array,
PRIMARY KEY (villageid)
);
/
【问题讨论】:
【参考方案1】:不清楚您想要的结果。
如果您只需要每个村庄中所有居民的总和,则不需要成员函数(“bool”[1/0] 也不需要)。
在 Column-Inline-Query 中使用 SUM
函数:
SELECT T.VILLAGEID,
T.VILLAGE_NAME,
(SELECT SUM(T2.NO_OF_RESIDENTS)
FROM TABLE(T.HOUSES) T2) SUM_RESIDENTS
FROM VILLAGE T;
我使用以下示例进行了一些更改:
SET SERVEROUTPUT ON;
SET FEEDBACK OFF;
CLEAR;
CREATE TYPE HOUSE AS OBJECT
(
HOUSE_NO NUMBER,
ROAD_NAME VARCHAR2(255),
POSTCODE VARCHAR2(10),
NO_OF_RESIDENTS NUMBER,
MEMBER FUNCTION PASS(H HOUSE) RETURN NUMBER
);
/
CREATE OR REPLACE TYPE BODY HOUSE AS
MEMBER FUNCTION PASS(H HOUSE) RETURN NUMBER IS
BEGIN
IF (H.HOUSE_NO = HOUSE_NO) AND (H.ROAD_NAME = ROAD_NAME) AND (H.POSTCODE = POSTCODE) AND (H.NO_OF_RESIDENTS = NO_OF_RESIDENTS) THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END;
END;
/
CREATE OR REPLACE TYPE HOUSES_ARRAY IS VARRAY(50) OF HOUSE;
/
CREATE TABLE VILLAGE (
VILLAGEID NUMBER,
VILLAGE_NAME VARCHAR2(25),
HOUSES HOUSES_ARRAY,
PRIMARY KEY (VILLAGEID)
);
INSERT INTO village(VILLAGEID,VILLAGE_NAME,HOUSES) VALUES (1,'Village_1',HOUSES_ARRAY(HOUSE(1,'Road_1',12000,10),HOUSE(2,'Road_1',12000,2)));
INSERT INTO village(VILLAGEID,VILLAGE_NAME,HOUSES) VALUES (2,'Village_2',HOUSES_ARRAY(HOUSE(1,'Road_2',12010,5),HOUSE(2,'Road_2',12010,20)));
SELECT T.VILLAGEID,
T.VILLAGE_NAME,
(SELECT SUM(T2.NO_OF_RESIDENTS)
FROM TABLE(T.HOUSES) T2) SUM_RESIDENTS
FROM VILLAGE T;
ROLLBACK;
DROP TABLE VILLAGE;
DROP TYPE HOUSES_ARRAY;
DROP TYPE HOUSE;
输出:
VILLAGEID VILLAGE_NAME SUM_RESIDENTS
---------- ------------------------- -------------
1 Village_1 12
2 Village_2 25
SQL>
或
SELECT T.VILLAGEID,
T.VILLAGE_NAME,
SUM(T2.NO_OF_RESIDENTS) SUM_RESIDENTS
FROM VILLAGE T,
TABLE(T.HOUSES) T2
GROUP BY T.VILLAGEID,
T.VILLAGE_NAME
;
注意过多的上下文更改 (SQLPLSQL)。 如果你能用 SQL 做,那就用 SQL 做。
【讨论】:
以上是关于返回另一个对象中列总和的成员函数的主要内容,如果未能解决你的问题,请参考以下文章