create table items
(
itemid varchar(5) not null primary key,
itemname varchar(25) not null,
/* other columns, e.g., unit_price, measurement_unit */
)
create table bom
(
itemid varchar(5) not null references items,
containsid varchar(5) not null references items,
qty int not null
/* other columns, e.g., quantity */
primary key(itemid, containsid),
check (itemid <> containsid)
)
set nocount on
insert into items(itemid, itemname) values('a', 'item a')
insert into items(itemid, itemname) values('b', 'item b')
insert into items(itemid, itemname) values('c', 'item c')
insert into items(itemid, itemname) values('d', 'item d')
insert into items(itemid, itemname) values('e', 'item e')
insert into items(itemid, itemname) values('f', 'item f')
insert into items(itemid, itemname) values('g', 'item g')
insert into items(itemid, itemname) values('h', 'item h')
insert into items(itemid, itemname) values('i', 'item i')
insert into items(itemid, itemname) values('j', 'item j')
insert into items(itemid, itemname) values('k', 'item k')
insert into bom(itemid, containsid, qty) values('e', 'j', 1)
insert into bom(itemid, containsid, qty) values('c', 'e', 3)
insert into bom(itemid, containsid, qty) values('a', 'c', 2)
insert into bom(itemid, containsid, qty) values('h', 'c', 4)
insert into bom(itemid, containsid, qty) values('c', 'b', 2)
insert into bom(itemid, containsid, qty) values('b', 'f', 1)
insert into bom(itemid, containsid, qty) values('b', 'g', 3)
insert into bom(itemid, containsid, qty) values('a', 'b', 2)
insert into bom(itemid, containsid, qty) values('a', 'd', 2)
insert into bom(itemid, containsid, qty) values('h', 'i', 1)
--以下 cte 計算數量的累積乘積:
with bomcte(itemid, containsid, qty, cumulativeqty,level)
as
(
select *, qty ,0
from bom
where itemid = 'a'
union all
select bom.*, bom.qty * bomcte.cumulativeqty, bomcte.level+1
from bom
join bomcte
on bom.itemid = bomcte.containsid
)
select * from bomcte
SQLSERVER 2005 遞迴查詢
專案中有使用者組表usergroup如下 其中pid表示當前組的上級組 表資料如下 現在想查詢出頂級組 沒有上級組叫頂級組 a1組的所有子孫組id,sql如下 查詢子節點 with rtd1 as select id pid from usergroup rtd2 as select from rt...
SQLSERVER 2005 遞迴查詢
專案中有使用者組表usergroup如下 其中pid表示當前組的上級組 表資料如下 現在想查詢出頂級組 沒有上級組叫頂級組 a1組的所有子孫組id,sql如下 查詢子節點 with rtd1 as select id pid from usergroup rtd2 as select from rt...
SQLServer2005下的遞迴查詢
在sqlserver2005下,遞迴查詢可以通過公共表示式 cte 來實現。如下所示 withcolumntree projectid,parentid,columnid,columnname,columnurl,ifdel,tag,clevel as select projectid,parent...