sql 查询以在 case 语句中再次获取列值

sql query to get the column value again in case statement

select *, 
case when number = '12' and status = 'y' then cost
end as [price]
from tblx

我从上面的查询中得到了结果,我想使用价格列的值,再次用于与下面相同的查询的 case 语句

select *, 
case when number = '12' and status = 'y' then cost-500
end as [price],
case when price = 24 then trasdate end as [trasdate]
from tblx

如果我的问题不清楚,请给我建议

我在一个存储过程中工作,该存储过程有两个以上的连接连接 8 个表,我只想再次获取列值以在同一查询的 case 语句中使用它,我缩短了问题,因为查询更大.

谢谢

select *, 
   case when number = '12' and status = 'y' then cost end price,
   case when number = '12' and status = 'y' 
         and cost = 24 then trasdate end [trasdate]
from tblx

在同一个查询中,您只需要在您尝试引用它的地方复制同一个 case 语句。顺便说一句,你应该给它添加一个 else 0 因为目前它会 return null 如果你的条件不评估为 true 这可能会影响它在其他 case 语句中的使用。

如果您不想重复 case 语句,还有其他选项,例如:

  • 在子查询中使用价格语句并在外部查询中按名称引用它
  • 使用临时 table 并将价格添加为计算列
  • 如上但使用 table 变量

只是重复声明显然是最简单的,也可能表现得最好,缺点是重复。在性能方面,针对您可能的用例进行测试。