在sql中对一列进行求和并按其进行分组

时间:2013-09-10 13:01:41

标签: sql group-by

所以基本上我有下面的查询。我想总结第二和第三列和第四列。我正在通过shiptoaddrressno和shiptoname进行分组。是否有可能使用原始的quantityshipped和extendedprice值计算出第四列中的等式?计算已关闭,因为我正在对列进行求和以使查询起作用。

declare @rundate datetime
set @rundate = '3/11/2013'


Declare @Sales table (ShipToAddressNo int, ShipToName varchar(40), SumOfQuantityShipped int, 
                        SumOfAmountShipped money, TotalDeductions float)
INSERT INTO @Sales
SELECT
    ShipToAddressNo,
    ShipToName,
    sum(QuantityShipped),
    sum(ExtendedPrice),
    (p.[Transfer Price] * QuantityShipped) +
    (p.[Profit Split Calculation 1 (Prasco Distribution Allowance)] * QuantityShipped) +
    (p.[Profit Split Calculation 2 (Share to Partner)] * QuantityShipped) +
    (p.[Profit Split Calculation 3 (Cost Adjustment)] * QuantityShipped) +
    (p.[Profit Split Calculation  (Cost Adjustment)] * QuantityShipped) +
    (p.[Net Sales Profit Split] * QuantityShipped) TotalDeductions --Sum this entire line 
FROM
    SalesSummary ss join [Product] p 
        on ss.ShortItemNo = p.SDITM
    join JDE_PRODUCTION.PRODDTA.F4101 im 
        on im.IMITM = p.SDITM
WHERE 
    InvoiceDate = @RunDate
GROUP BY
    ShipToAddressNo,
    ShipToName

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

sum((p.[Transfer Price] * QuantityShipped) +
    (p.[Profit Split Calculation 1 (Prasco Distribution Allowance)] * QuantityShipped) +
    (p.[Profit Split Calculation 2 (Share to Partner)] * QuantityShipped) +
    (p.[Profit Split Calculation 3 (Cost Adjustment)] * QuantityShipped) +
    (p.[Profit Split Calculation  (Cost Adjustment)] * QuantityShipped) +
    (p.[Net Sales Profit Split] * QuantityShipped)
   ) as TotalDeductions --Sum this entire line