成员函数返回另一个对象中列的总和

时间:2016-02-01 21:47:40

标签: arrays object plsql sqlplus

我目前在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 个答案:

答案 0 :(得分:0)

不完全清楚您想要的结果。

如果您只需要每个村庄的所有居民的总和,您不需要成员函数(既不是“bool”[1/0])。

使用SUM函数代替Column-Inline-Query:

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
;

注意过多的上下文更改(SQL< - > PLSQL) 如果您可以使用SQL,请使用SQL。