SQL 中樹形結構查詢的運用

2021-06-07 17:26:59 字數 2504 閱讀 9213

use tempdb

go-- 建立演示環境

create table dept(

id int primary key, 

parent_id int,

name nvarchar(20))

insert dept

select 0, 0, n'《全部》' union all

select 1, 0, n'財務部' union all

select 2, 0, n'行政部' union all

select 3, 0, n'業務部' union all

select 4, 0, n'業務部' union all

select 5, 4, n'銷售部' union all

select 6, 4, n'mis' union all

select 7, 6, n'ui' union all

select 8, 6, n'軟體開發' union all

select 9, 8, n'內部開發'

go-- 查詢指定部門下面的所有部門

declare @dept_name nvarchar(20)

set @dept_name = n'mis'

;with

depts as(

-- 定位點成員

select * from dept

where name = @dept_name

union all

-- 遞迴成員, 通過引用cte自身與dept基表join實現遞迴

select a.*

from dept a, depts b

where a.parent_id = b.id

)select * from depts

go-- 刪除演示環境

drop table dept

----cte的綜合應用

use tempdb

go-- 建立演示環境

create table dept(

id int primary key, 

parent_id int,

name nvarchar(20))

insert dept

select 0, 0, n'《全部》' union all

select 1, 0, n'財務部' union all

select 2, 0, n'行政部' union all

select 3, 0, n'業務部' union all

select 4, 0, n'業務部' union all

select 5, 4, n'銷售部' union all

select 6, 4, n'mis' union all

select 7, 6, n'ui' union all

select 8, 6, n'軟體開發' union all

select 9, 8, n'內部開發'

go-- 查詢指定部門下面的所有部門, 並彙總各部門的下級部門數

declare @dept_name nvarchar(20)

set @dept_name = n'mis'

;with

depts as(   -- 查詢指定部門及其下的所有子部門

-- 定位點成員

select * from dept

where name = @dept_name

union all

-- 遞迴成員, 通過引用cte自身與dept基表join實現遞迴

select a.*

from dept a, depts b

where a.parent_id = b.id

),deptchild as(  -- 引用第1個cte,查詢其每條記錄對應的部門下的所有子部門

select 

dept_id = p.id, c.id, c.parent_id

from depts p, dept c

where p.id = c.parent_id

union all

select 

p.dept_id, c.id, c.parent_id

from deptchild p, dept c

where p.id = c.parent_id

),deptchildcnt as( -- 引用第2個cte, 彙總得到各部門下的子部門數

select 

dept_id, cnt = count(*)

from deptchild

group by dept_id

)select    -- join第1,3個cte,得到最終的查詢結果

d.*,

childdeptcount = isnull(ds.cnt, 0)

from depts d

left join deptchildcnt ds

on d.id = ds.dept_id

go-- 刪除演示環境

drop table dept

SQL 樹形結構遞迴查詢

with as短語,也叫做子查詢部分 subquery factoring 定義乙個sql 片段,改sql 片段會被整個sql語句用到。其中最實用的功能就是資料的遞迴,遞迴的原理 遞迴包括至少兩個查詢,乙個查詢作為遞迴的基點也就是起點,另乙個查詢作為遞迴的成員。with temp as select...

遞迴查詢樹形結構的SQL

一.在oracle中可使用start with.connect by子句 start with.connect by子句遞迴查詢一般用於乙個表維護樹形結構的應用。建立示例表 create table tbl test id number,name varchar2 100 byte pid numb...

SQL查詢的運用

1.運輸確認 運輸證選擇 not in 自連線,內連線 select distinct t0.u transportarno as 運輸證編號 t0.u fromdate as 有效期從 t0.u todate as 有效期到 t0.u itemcode as 物料 t0.u itemname as...