在当前 table 中使用 cte

Using cte inside current table

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

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

select distinct TableName,ex1 from InventoryTransTemp  where Active=1

我收到无效列名错误 'ex1'。 我希望 ex1 的总和与 select 状态下的当前 table 相关联,并且还具有 where 子句,例如 active=1

更具体地对 HasItems!=0 的每个 TableName 中的所有行求和

然后你可以使用子查询。

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