将一列显示2个数据总和的列连接在一起

时间:2019-02-28 09:52:01

标签: sql join group-by aggregate

SELECT o.ProductID ,
       p.ProductName ,
       o.unitprice AS UnitCost ,
       sum(o.Quantity) AS TotalUnitsSold ,
       (sum(o.Quantity)*o.unitprice) AS FinalCost
FROM OrderDetails o
JOIN Products p ON o.ProductID = p.ProductID
GROUP BY o.ProductID ,
         p.ProductName ,
         o.unitprice
ORDER BY 1

我想在“最终成本”旁边再留一列,该列给出了产品总数, 蔡的简写应该是2505.60+11772.00

sql output

预期o / p

ProductID    ProductName    UnitCost    TotalUnitsSold    FinalCost       Total
1                Chai            14.40        174           2505.60          14277.60
1                Chai            18.00        654           11772.00         Null

1 个答案:

答案 0 :(得分:0)

您可以使用窗口函数,它将为所有行求和:

SELECT  T.ProductID
,       T.ProductName
,       T.UnitCost
,       T.TotalUnitsSold
,       T.FinalCost
,       SUM(T.FinalCost) OVER(PARTITION BY ProductID) AS Total
FROM    (
            SELECT o.ProductID ,
                   p.ProductName ,
                   o.unitprice AS UnitCost ,
                   sum(o.Quantity) AS TotalUnitsSold ,
                   (sum(o.Quantity)*o.unitprice) AS FinalCost
            FROM OrderDetails o
            JOIN Products p ON o.ProductID = p.ProductID
            GROUP BY o.ProductID ,
                     p.ProductName ,
                     o.unitprice
        ) AS T
ORDER BY 1