SQL constructs table hierarchies and recursively accumulates data

Source: Internet
Author: User

Build a table's parent-child relationship

There is a requirement that there is no relationship between the data in the table, just like a type, there are multiple warehouse picking times.

Code

-- Build a table's parent-child relationship
-- Hierarchical relationship between products
-- Build with row_number (). The top level is 0.
Insert   Into Stock
( [ No ]   -- 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 Inner   Join Po B On A. posysno = B. sysno
And B. Status = 4 ) T

Effect

 

Code

-- Recursively accumulate the number of warehouse receiving for the same product
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, 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
)

--View data
Select * From
Product_cte1Option(Maxrecursion0)

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.