在当前表中使用CTE

时间:2018-11-07 16:30:25

标签: sql-server sql-server-2008-r2

我正在尝试创建一个表达式,请参见下面的示例。

with cte1  (ex1)
as
(
 select SUM(HasItems) 
 from InventoryTransTemp where HasItems !=0 
) 

select distinct TableName,ex1 from InventoryTransTemp  where Active=1

我遇到错误无效的列名'ex1'。 我希望来自ex1的总和与处于选择状态的当前表连接,并且还具有where子句,例如active = 1

更具体地来说,是将每个TableName中具有HasItems!= 0的所有行相加

1 个答案:

答案 0 :(得分:1)

然后您可以使用子查询。

select distinct 
   TableName
   ,ex1 = (select SUM(HasItems) from InventoryTransTemp where HasItems !=0 )
from InventoryTransTemp  
where Active=1

如果表相关,那么您需要关联子查询或简单地联接表。

select distinct 
   t.TableName
   ,ex1 = (select SUM(t2.HasItems) 
           from InventoryTransTemp t2 
           where t2.HasItems !=0 
                 and t1.somecolumn = t2.somecolumn)
from InventoryTransTemp t  
where t.Active=1