简体   繁体   中英

Find The Top Level Parent And Multiply Quantities

I have two tables which track part numbers as well as the hierarchy of assemblies.

Table: Config

ConfigNum  AssemblyNum  Qty
 1            A        1
 1            B        2
 1            C        2
 2            A        1
 2            C        1

Table: SubAssembly

 SubAssembly  PartNum  Qty
 A          AA     2
 A          BB     4
 A          CC     2
 A          DD     4
 B          EE     4
 B          FF     8
 AA         AAA    2

I would like to create a flat version of these tables which shows the ConfigNum (Top level parent) with all associated assembly and part numbers, for each ConfigNum in the Config table. The column Config.AssemblyNum is equivalent to SubAssembly.SubAssembly .

For this problem I think you must use a recursive query. In fact I think SubAssembly table should have some ProductID field other than SubAssembly to easily identify the main product that contains assemblies.

You can find a similar example in SLQ Server documentation.

Can check it here: http://rextester.com/FQYI80157

Change the Qty in Config table to change the final result.

create table #t1 (cfg int, part varchar(10), qty int);
create table #t2 (part varchar(10), sasm varchar(10), qty int);
insert into #t1 values (1,'A',2);
insert into #t2 values ('AA','AAA',2),('A','AA',2),('A','BB',4),('A','CC',2),('A','DD',4);

WITH cte(sasm, part, qty) 
AS (
    SELECT sasm, part, qty 
    FROM #t2 WHERE part = 'A'

    UNION ALL

    SELECT p.sasm, p.part, p.qty * pr.qty
    FROM cte pr, #t2 p
    WHERE p.part = pr.sasm
  )
SELECT #t1.cfg, cte.part, cte.sasm, SUM(cte.qty * COALESCE(#t1.qty,1)) as total_quantity
FROM cte
left join #t1 on cte.part = #t1.part
GROUP BY #t1.cfg, cte.part, cte.sasm;

This is the result:

+---+------+------+------+----------------+
|   | cfg  | part | sasm | total_quantity |
+---+------+------+------+----------------+
| 1 | NULL | AA   | AAA  |              4 |
| 2 | 1    | A    | AA   |              4 |
| 3 | 1    | A    | BB   |              8 |
| 4 | 1    | A    | CC   |              4 |
| 5 | 1    | A    | DD   |              8 |
+---+------+------+------+----------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM