如何用Oracle實現組織圖中的匯總統計

來源:互聯網
上載者:User

對於一般的資料模型來說,一般是有一個事實表,若干個維度資料表,通過事實表與維度資料表的串連,實現不同層次的查詢匯總。

問題是對於組織圖而言,一般所有的資料都存貯於一個表中,而且,組織圖的層次也是動態。那麼,在這種情況下,如何?員工工資的匯總呢?一個比較有趣的問題是: 如何統計員工及其所有被管理員工的總工資,舉個例子,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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.