如何根据 parent 列值获取包含 parent 在内的所有 child 记录的事实列(屏幕截图)

How to get the Fact column (screenshot) populate for all child records including parent based on parent column value

如何为所有行 (parent + child) 生成事实列? parent 的 RefTotalTransAmountPackage 列应与所有其他 7 行的 DistributedPercentage 列相乘

假设我理解您的要求,您可以尝试以下操作:

DECLARE @tempFactItemTagsAssignment table (
    ID int, ParentOrderItemID int, RefTotalTransAmountPackage decimal(18,4), DistributedPercentage decimal(18,2)
);

INSERT INTO @tempFactItemTagsAssignment VALUES
    ( 382904448, 382904445, 0, 0 ),
    ( 382904446, 382904445, 0, 27.49 ),
    ( 382904446, 382904445, 0, 27.49 ),
    ( 382904446, 382904445, 0, 0.83 ),
    ( 382904446, 382904445, 0, 27.49 ),
    ( 382904445, NULL, 77.99, 16.70 ),
    ( 382904447, 382904445, 0, 0 );

DECLARE @ParentId int = 382904445;

SELECT
    x.ID,
    x.ParentOrderItemID,
    x.RefTotalTransAmountPackage,
    x.DistributedPercentage,
    p.ParentRefTotal,
    CAST ( ( p.ParentRefTotal * ( x.DistributedPercentage / 100 ) ) AS decimal(18,2) ) AS Fact
FROM @tempFactItemTagsAssignment AS x
OUTER APPLY (

    SELECT RefTotalTransAmountPackage AS ParentRefTotal FROM @tempFactItemTagsAssignment AS n
        WHERE n.ID = @ParentId AND n.ParentOrderItemID IS NULL

) AS p
WHERE
    x.ID = @ParentId OR x.ParentOrderItemID = @ParentId
ORDER BY
    ID;

Returns

+-----------+-------------------+----------------------------+-----------------------+----------------+-------+
|    ID     | ParentOrderItemID | RefTotalTransAmountPackage | DistributedPercentage | ParentRefTotal | Fact  |
+-----------+-------------------+----------------------------+-----------------------+----------------+-------+
| 382904445 | NULL              | 77.9900                    | 16.70                 | 77.9900        | 13.02 |
| 382904446 | 382904445         | 0.0000                     | 27.49                 | 77.9900        | 21.44 |
| 382904446 | 382904445         | 0.0000                     | 27.49                 | 77.9900        | 21.44 |
| 382904446 | 382904445         | 0.0000                     | 0.83                  | 77.9900        | 0.65  |
| 382904446 | 382904445         | 0.0000                     | 27.49                 | 77.9900        | 21.44 |
| 382904447 | 382904445         | 0.0000                     | 0.00                  | 77.9900        | 0.00  |
| 382904448 | 382904445         | 0.0000                     | 0.00                  | 77.9900        | 0.00  |
+-----------+-------------------+----------------------------+-----------------------+----------------+-------+