在SUM函数中引用ALIAS - SQL Server

时间:2018-04-18 16:23:40

标签: sql sql-server sum alias

背景:

我正在尝试计算查询内部的利润率,而且我遇到了错误。当我尝试在SUM函数中使用select语句时,我会触发错误:

  

无法对包含
的表达式执行聚合函数   聚合或子查询。

据我所知,这是由SUM函数内部的SELECT查询引起的。从那里,我试图引用COGS列的别名。我也这样做时收到错误:

  

列名称无效' COGS'。

在再次讨论查询之后,我想可能是因为我在SUM函数中尝试了所有这些,所以我删除了它并运行查询。它返回了一些错误:

  
      
  • 专栏' tbl_invoice.subTotal'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
  •   
  • 专栏' tbl_invoice.tradeinAmount'在选择列表中无效,因为它不包含在聚合函数或   GROUP BY条款。
  •   
  • 专栏' tbl_invoice.subTotal'在选择列表中无效,因为它不包含在聚合函数或   GROUP BY条款。
  •   
  • 专栏' tbl_invoice.tradeinAmount'在选择列表中无效,因为它不包含在聚合函数或   GROUP BY子句。
  •   
  • 专栏' tbl_invoice.subTotal'在选择列表中无效,因为它不包含在聚合函数或   GROUP BY条款。
  •   
  • 专栏' tbl_invoice.tradeinAmount'在选择列表中无效,因为它不包含在聚合函数或   GROUP BY条款。
  •   

是否有另一种方法可以在SUM函数中使用或引用我需要的值?

查询:

--Main query
SELECT 
custID,
COUNT(custID) AS InvoiceNum,

--This is the column that has an alias
(SELECT cogs FROM #tempMarketing where #tempMarketing.custID = tbl_invoice.custID) as COGS,
--This is where I am trying to calculate the profit margin
SUM(((((subTotal + (-1 * tradeinAmount) - (SELECT cogs FROM #tempMarketing where #tempMarketing.custID = tbl_invoice.custID))) 
/ (NULLIF(subTotal + (-1 * tradeinAmount),0))) *100)) as Profitmargin, 

FROM tbl_invoice 
group by custID
order by InvoiceNum desc;

2 个答案:

答案 0 :(得分:2)

SELECT 
a.custID,
COUNT(a.custID) AS InvoiceNum,  case when a.custid=b.custid then b.cogs else 0 end 
 as COGS,
SUM(((((subTotal + (-1 * tradeinAmount) - case when a.custid=b.custid then b.cogs else 0 end)) 
/ (NULLIF(subTotal + (-1 * tradeinAmount),0))) *100)) as Profitmargin, 

FROM tbl_invoice a 
left join #tempMarketing b on a.custID =b.custid
group by a.custID, 
case when a.custid=b.custid then b.cogs else null end 
order by InvoiceNum desc;

答案 1 :(得分:1)

您可以尝试以下查询,我为cogs列创建了一个公用表表达式:

WITH cte_base AS(
SELECT cogs FROM #tempMarketing where #tempMarketing.custID = tbl_invoice.custID
)
SELECT 
custID,
COUNT(custID) AS InvoiceNum,

--This is the column that has an alias
cte_base.cogs as COGS,
--This is where I am trying to calculate the profit margin
SUM(((((subTotal + (-1 * tradeinAmount) - (cte_base.cogs))) 
/ (NULLIF(subTotal + (-1 * tradeinAmount),0))) *100)) as Profitmargin, 

FROM tbl_invoice 
group by custID
order by InvoiceNum desc;