汇总不同的行

时间:2018-08-21 17:39:53

标签: sql sum distinct

我试图获得每个部分的总和,但是由于某些原因,它没有给我这段代码的总和。它根据子查询中的记录数重复相同的部件号。我在做什么错了?

Select Distinct IIF(x.omlPartID in ('10027','10028')
    ,x.omlPartID
    ,x.jmaPartID) as PartID
    , Sum(Cast(Total_Quantity as INT)) as SumTot
From (
    SELECT distinct SalesOrderLines.omlsalesorderID
        , salesorderlines.omlSalesOrderLineID
        , SalesOrderLines.omlPartID
        , JobAssemblyMaterialCombo2 .jmaPartID
        ,  (
            IIF(rtrim(SalesOrderLines.omlPartID) in ('10027','10028')
            , 1
            , JobAssemblyMaterialCombo2.jmaQuantityPerParent
            ) * SalesOrderLines.omlOrderQuantity
            ) As 'Total_Quantity'
    FROM M1_HB.dbo.SalesOrderLines SalesOrderLines 
    Left Outer Join M1_HB.dbo.SalesOrderJobLinks SalesOrderJobLinks 
        On SalesOrderLines.omlSalesOrderID = SalesOrderJobLinks.omjSalesOrderID 
            AND SalesOrderlines.omlSalesOrderLineID = SalesOrderJobLinks.omjSalesOrderLineID 
    Left Outer Join M1_HB.dbo.Jobs Jobs 
        on SalesOrderJobLinks.omjJobID = Jobs.jmpJobID 
    Left Outer Join M1_HB.dbo.JobAssemblyMaterialCombo2 JobAssemblyMaterialCombo2 
        On Jobs.jmpJobID = JobAssemblyMaterialCombo2. jmaJobID 
    Left Outer Join M1_HB.dbo.SalesOrders SalesOrders 
        On SalesOrderLines.omlSalesOrderID = SalesOrders.ompSalesOrderID 
    Left Outer Join M1_HB.dbo.Organizations Organizations 
        On SalesOrders.ompCustomerOrganizationID = Organizations.cmoOrganizationID 
    WHERE JobAssemblyMaterialCombo2 .jmaPartID in ('10027','10028') 
        or (
            SalesOrderLines.omlPartID in ('10027','10028') 
            and 
            JobAssemblyMaterialCombo2 .jmaPartID is Null
            )
) x
Group by x.omlPartID, x.jmaPartID

1 个答案:

答案 0 :(得分:0)

似乎您需要按PartID分组

index.html

,您可以使用别名表名称来简化文本,例如

project_repo