SQL构建表层次关系,递归累加数据
构建表的上下级关系
有一个需求,表中数据没有关系,如同一个类型的,有多个出库时间。
代码
--构建表的上下级关系
--可以对同一个产品的,有层次关系
--使用ROW_NUMBER(),来构建,最上上一级为0
INSERT INTO Stock
([no] --编号
,[quantity]
,[id]
,[productsysno]
,[intime]
,[parentid])
select no, id,productsysno,id-1 parentid from (
select a.NO, a.quantity,ROW_NUMBER() over(partition by a.productsysno order by b.intime ASC) id ,
productsysno,intime from dbo.PO_It a inner join PO b on a.POSysNo=b.SysNo
and b.status=4 ) t
--可以对同一个产品的,有层次关系
--使用ROW_NUMBER(),来构建,最上上一级为0
INSERT INTO Stock
([no] --编号
,[quantity]
,[id]
,[productsysno]
,[intime]
,[parentid])
select no, id,productsysno,id-1 parentid from (
select a.NO, a.quantity,ROW_NUMBER() over(partition by a.productsysno order by b.intime ASC) id ,
productsysno,intime from dbo.PO_It a inner join PO b on a.POSysNo=b.SysNo
and b.status=4 ) t
效果如图:
代码
--递归累加同一产品的入库数量
with product_cte1(sysno,productsysno,id,lastqty,quantity,Level)
as
(
SELECT [poitemsysno], productsysno,id,quantity,quantity,1 Level from Item_Stock where parentid=0
UNION ALL
SELECT e.[poitemsysno],e.productsysno,e.ID ID,d.quantity,e.quantity+d.quantity,Level+1
FROM dbo.Item_Stock AS e,product_cte1 AS d
where e.parentid = d.id and e.productsysno=d.productsysno
)
--查看数据
select * from
product_cte1 OPTION (MAXRECURSION 0)
with product_cte1(sysno,productsysno,id,lastqty,quantity,Level)
as
(
SELECT [poitemsysno], productsysno,id,quantity,quantity,1 Level from Item_Stock where parentid=0
UNION ALL
SELECT e.[poitemsysno],e.productsysno,e.ID ID,d.quantity,e.quantity+d.quantity,Level+1
FROM dbo.Item_Stock AS e,product_cte1 AS d
where e.parentid = d.id and e.productsysno=d.productsysno
)
--查看数据
select * from
product_cte1 OPTION (MAXRECURSION 0)