嗨我有一些使用*的T-SQL的问题

时间:2017-06-14 01:04:51

标签: sql tsql cross-apply

对ProductID订单进行分组,按ProductID获取总计,订单总数以及代表总订单的ProductID订单(即百分比)。所需列:PercenofTotal(UnitPrice * Quantity),TotalAmount(UnitPrice * Quantity),PercentofTheTotal(UnitPrice * Quantity)

所以这是我的代码,我不知道的是执行percentofTheTotal和TotalAmount

SELECT P.ProductID, (P.UnitPrice * ODQuantity) AS tOTALaMOUNTByProductID, (P.UnitPrice * Quantity) as TotalAmount , (P.UnitPrice * OD.Quantity) as PercenofTotal 
From Products as P,
From OrderDetails as OD
Group by P.ProductID

1 个答案:

答案 0 :(得分:0)

你正在尝试用不正确的简单陈述做一些复杂的事情。这样的事情可能会做你想要达到的目标。

USE AdventureWorks2014
GO

SELECT  P.ProductID
       , SUM(P.StandardCost * OD.OrderQty) AS TotalAmountByProductID
       , MAX(SumTA.TotalAmount) AS TotalAmount 
       , (SUM(P.StandardCost * OD.OrderQty) / (MAX(SumTA.TotalAmount))*100) AS PercentOfTotal
FROM Production.Product as P
INNER JOIN Sales.SalesOrderDetail as OD on P.ProductID = OD.ProductID
LEFT OUTER JOIN (
                   SELECT max(pid) as pid, SUM(TA.TotalAmount) as TotalAmount
                    FROM
                       (  SELECT  '1' as pid, P.ProductID, SUM(P.StandardCost * OD.OrderQty) AS TotalAmount
                         FROM Production.Product as P
                         JOIN Sales.SalesOrderDetail as OD on P.ProductID = OD.ProductID
                          Group by P.ProductID
                       )AS TA
                ) AS SumTA ON SumTA.pid = '1'

Group by P.ProductID
ORDER BY PercentOfTotal Desc