我需要获得Alias专栏的%保证金,并且它让我烦恼,我说得不对,而且可能很简单。
我的查询是我正在使用的内容,我通过从OH.TotalSellPrice
列中减去OH.TotalCostPrice
来创建了列Profit。我需要获得%保证金,因此我需要SUM
新创建的列,将其除以OH.TotalSellPrice
列,然后* 100
以获得保证金。
SELECT U.Name AS [Created By],
SUM(OH.TotalSellPrice) as [Sale value],
SUM (OH.TotalSellPrice-OH.TotalCostPrice) as [Profit],
COUNT(OH.OrderID) / 100 AS ID1
FROM OrderHeader AS OH WITH(NOLOCK)
LEFT JOIN Users AS U WITH(NOLOCK) ON U.UserID = OH.CreatedByID
WHERE OH.Deleted = 0 AND OH.OrderType = 1
and U.UserID in (129,245,336,337,378,387,388,425,427,433,458,480, 489, 370,458)
and OH.Invoiced=1
GROUP BY U.Name
答案 0 :(得分:0)
您必须对聚合值而不是别名列名进行计算,如下所示:
(SUM(OH.TotalSellPrice-OH.TotalCostPrice) /
SUM(OH.TotalSellPrice))*100 AS PercentageMargin
因此完整查询将如下所示:
SELECT U.Name AS [Created By],
SUM(OH.TotalSellPrice) as [Sale value],
SUM (OH.TotalSellPrice-OH.TotalCostPrice) as [Profit],
COUNT(OH.OrderID) / 100 AS ID1,
(SUM (OH.TotalSellPrice-OH.TotalCostPrice) /
SUM(OH.TotalSellPrice))*100 AS PercentageMargin
FROM OrderHeader AS OH WITH(NOLOCK)
LEFT JOIN Users AS U WITH(NOLOCK) ON U.UserID = OH.CreatedByID
WHERE OH.Deleted = 0 AND OH.OrderType = 1
and U.UserID in (129,245,336,337,378,387,388,425,427,433,458,480, 489, 370,458)
and OH.Invoiced=1
GROUP BY U.Name