在表达式内部使用别名的选择语句

时间:2018-06-20 22:12:49

标签: sql-server pervasive-sql

是否可以在另一个表达式中使用一个表达式?我想基于收入(扩展)-商品成本(LMOZ)计算利润

正在寻找这样的东西:SUM(“扩展名”)-SUM(“ LMOZ”)作为获利。

样本查询:

Select distinct Top 10 rtrim(customer) as SaleCust,Sum(Extension) As Extension,
SUM(COST_Material) + SUM(Cost_Labor) + SUM(Cost_Outside) + SUM(Cost_Overhead) + SUM(Cost_Other) AS LMOZ 
From V_Order_Hist_Line 
Where Year(Date_Invoice) = 2018 AND Salesperson = 'DJW' AND PRODUCT_LINE LIKE 'R_' 
Group By rtrim(customer)
ORDER BY Extension desc

2 个答案:

答案 0 :(得分:0)

是的,请使用子查询在范围内获取列别名或再次重复所有操作。

子查询模板:

SELECT *, Extension - LMOZ AS Profit
FROM ( ... your query ... ) alias

已包含在您的查询中:

SELECT *, Extension - LMOZ AS Profit
FROM (
  SELECT DISTINCT TOP 10 
    rtrim(customer) AS SaleCust,
    SUM(Extension) AS Extension,
    SUM(COST_Material) + SUM(Cost_Labor) + SUM(Cost_Outside) + SUM(Cost_Overhead) + SUM(Cost_Other) AS LMOZ 
  FROM V_Order_Hist_Line 
  WHERE Year(Date_Invoice) = 2018 AND Salesperson = 'DJW' AND PRODUCT_LINE LIKE 'R_' 
  GROUP BY rtrim(customer)
  ORDER BY Extension DESC
) t

答案 1 :(得分:0)

您可以使用子查询,但在子查询中无法使用排序依据。您可以执行如下操作。

SELECT distinct Top 10 SaleCust, (Extension -  LMOZ) AS Calc, OrdExtension
FROM (
Select  rtrim(customer) as SaleCust,Sum(Extension) As Extension,
SUM(COST_Material) + SUM(Cost_Labor) + SUM(Cost_Outside) + SUM(Cost_Overhead) + SUM(Cost_Other) AS LMOZ,
ROW_NUMBER() OVER(ORDER BY Extension DESC) AS OrdExtension
From V_Order_Hist_Line 
Where Year(Date_Invoice) = 2018 AND Salesperson = 'DJW' AND PRODUCT_LINE LIKE 'R_' 
Group By rtrim(customer)
)
ORDER BY OrdExtension desc