对于一般的数据模型来说,一般是有一个事实表,若干个维度表,通过事实表与维度表的连接,实现不同层次的查询汇总。
问题是对于组织结构而言,一般所有的数据都存贮于一个表中,而且,组织结构的层次也是动态的。那么,在这种情况下,如何实现员工工资的汇总呢?一个比较有趣的问题是: 如何统计员工及其所有被管理员工的总工资,举个例子,CEO的总工资就是整个公司总有员工的总工资之和,包括他自己。
Oracle 引入了一个扩展的运算符,专门用来处理此种情形,它就是connect_by_root。当以connect_by_root修饰一个列名时,Oracle将返回根节点对应的此列的值。例如,当start with 为 last_name = ‘King’时,这时返回的所有行的connect_by_root last_name的值都将为’King’。这时,对所有行的累计就是对’King’的数据的累计了。当不指定start with 子句时,Oracle将对每个节点依次进行遍历,于是,我们可以对返回的结果对last_name进行一次group by,那么我们就得到了所有last_name对应的汇总工资了。
下面是Oracle 文档中的例子。
The following example returns the last name of each employee in department 110, each manager
above that employee in the hierarchy, the number of levels between manager and employee,
and the path between the two:
SELECT last_name "Employee", CONNECT_BY_ROOT last_name "Manager",LEVEL-1 "Pathlen", SYS_CONNECT_BY_PATH(last_name, '/') "Path"FROM employeesWHERE LEVEL > 1 and department_id = 110CONNECT BY PRIOR employee_id = manager_idORDER BY "Employee", "Manager", "Pathlen", "Path";
Employee Manager Pathlen Path--------------- --------------- ---------- ------------------------------Gietz Higgins 1 /Higgins/GietzGietz King 3 /King/Kochhar/Higgins/GietzGietz Kochhar 2 /Kochhar/Higgins/GietzHiggins King 2 /King/Kochhar/HigginsHiggins Kochhar 1 /Kochhar/HigginsThe following example uses a GROUP BY clause to return the total salary of each employee in department 110 and all employees below that employee in the hierarchy:
SELECT name, SUM(salary) "Total_Salary" FROM (SELECT CONNECT_BY_ROOT last_name as name, SalaryFROM employeesWHERE department_id = 110CONNECT BY PRIOR employee_id = manager_id)GROUP BY nameORDER BY name, "Total_Salary";
NAME Total_Salary------------------------- ------------Gietz 8300Higgins 20300King 20300Kochhar 20300