SQL Server:父/子级

时间:2016-07-06 21:47:16

标签: sql-server parent-child calculated-field

显示计算列时出现一些问题。

我为父项显示一行,然后为每个子项显示几行(1-5之间)。

我的第一个问题是:

Select 
    _r1 = pbhier.r1 
    , pb.parent_id
    , pb.Product_id
    , pb.LastCost 
    , pb.AverageCost 
    , pb.FirstDatePurchased 
    , lrd.LastReceivingDate 
    , inv_units = isnull(inv.quantity,0)
    , sales_units = convert(int,isnull(sales.SalesUnits,0)) 
    , number_months_supply = case when isnull(sales.salesUnits,0) = 0 then isnull(inv.quantity,0) 
                                  else 
                                    case when (isnull(sales.salesUnits,0)/12) = 0 then 0 
                                         else 
                                            (convert(int,(inv.quantity/(isnull(sales.salesUnits,0)/12)))) end end
    , inv.quantity, sales.SalesUnits
    , ext_AverageCost = isnull(inv.quantity,0) * pb.averagecost 
INTO #tempdata
From Products pb 
    inner join #TempFinalHier pbhier on pb.product_id = pbhier.product_id 
    left join #inventoryPC inv (nolock) on pb.product_id = inv.product_id 
    left join #tempTotSalesPC sales (nolock) on pb.product_id = sales.product_id 
    left join #lastReceivingDate lrd on lrd.rm_product_id = pb.product_id 
where pb.Parent_ID in (select parent_id from #FinalParentSelection)

这会创建一个临时数据集。 “number_months_supply”列不需要在上面计算,但在我的最终查询中应该使用相同的公式。我在下面的最终查询得到了最终的结果集:

    Select distinct
        H.R1 , H.R2, H.Lvl,
        case 
           when R1 <> R2 
              then H.parent_sku 
              else H.SKU 
        end as SKU, 
        H.parent_sku,
        FirstReceiptDate = min(B.FirstDatePurchased),
        LastReceiptDate = max(B.LastReceivingDate), 
        OnHand = sum(B.inv_units),
        SalesUnits = sum(B.sales_units), 
        case 
           when isnull(sum(B.sales_units),0) = 0 
              then isnull(sum(B.inv_units),0) 
              else 
                 case 
                    when (isnull(sum(B.sales_units),0)/12) = 0 
                    then 0 
                    else convert(decimal(10, 2), (sum(B.inv_units) / (isnull(sum(B.sales_units), 0) / 12)))  
                 end 
        end,
        max(B.ext_AverageCost) as ext_AverageCost
    From 
        #TempFinalHier H
    join 
        #TempData1 B on (B._R1 between H.R1 and H.R2)
--  where H.Lvl=1       --Show only parent line
    Group By
        H.R1, H.R2, H.Lvl, H.parent_sku
    having 
        sum(B.number_months_supply) > 12    --@MonthsSupplyGreaterThanOrEqual
    Order by    
        R1

我想要的是: 父行(lvl1)的'onHand'需要是所有子行(lvl2)的总和。同样适用于'SalesUnits'。最后,Number_months_supply公式为(inv / sales_units)* 12。我想将number_months_supply显示为带有2个小数点的数字。

希望得到一些帮助。

感谢。

0 个答案:

没有答案