我如何在where子句中使用别名? [重复]

问题描述 投票:19回答:4

可能重复:Referring to a Column Alias in a WHERE Clause

   SELECT
Trade.TradeId, 
Isnull(Securities.SecurityType,'Other') SecurityType, 
TableName,
CASE 
WHEN 
SecurityTrade.SecurityId IS NOT NULL  
THEN 
SecurityTrade.SecurityId
ELSE 
Trade.SecurityId
END AS PricingSecurityID,
sum(Trade.Quantity)OVER(Partition by Securities.SecurityType, SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity,
--added porfolio id for Getsumofqantity
Trade.PortfolioId,

Trade.Price,
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position
from
Fireball_Reporting..Trade

where porfolioid =5 and Position =1   

我想在我的where子句中使用Position = 1,这是大小写的别名

case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position

如何在where子句中使用它?

我尝试在where子句中直接使用该CASE语句,但失败了请帮助我

WHERE Trade.SecurityId = @SecurityId AND PortfolioId = @GHPortfolioID AND
                (case when (Buy = 1 and Long = 1) then 1 when (Buy = 0 and Long = 0) then 1 else 0 end Position = 1)
sql sql-server qtsql
4个回答
46
投票
column_alias可以在ORDER BY子句中使用,但

不能在WHERE,GROUP BY或HAVING子句中使用

MySQL doc类似,它说:

标准SQL

不允许在WHERE子句中引用列别名

。之所以施加此限制,是因为在评估WHERE子句时,可能尚未确定列值。

但是在

MySQL

中,您可以使用一些trick to overcome this

20
投票
SELECT * FROM ( SELECT Trade.TradeId, Isnull(Securities.SecurityType,'Other') SecurityType, TableName, CASE WHEN SecurityTrade.SecurityId IS NOT NULL THEN SecurityTrade.SecurityId ELSE Trade.SecurityId END AS PricingSecurityID, sum(Trade.Quantity)OVER(Partition by Securities.SecurityType, SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity, --added porfolio id for Getsumofqantity Trade.PortfolioId, Trade.Price, case when (Buy = 1 and Long = 1) then 1 when (Buy = 0 and Long = 0) then 1 else 0 end Position from Fireball_Reporting..Trade where porfolioid = 5 ) AS data WHERE Position = 1

这意味着您不需要在CASE子句中重复WHERE语句。 (可维护和干燥)。

这也是允许优化器表现为

仿佛您

had只是在WHERE子句中重复自己的结构。

它对于其他RDBMS也是非常可移植的。

在SQL Server中,然后您还有另一个选择...

SELECT Trade.TradeId, Isnull(Securities.SecurityType,'Other') SecurityType, TableName, CASE WHEN SecurityTrade.SecurityId IS NOT NULL THEN SecurityTrade.SecurityId ELSE Trade.SecurityId END AS PricingSecurityID, sum(Trade.Quantity)OVER(Partition by Securities.SecurityType, SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity, --added porfolio id for Getsumofqantity Trade.PortfolioId, Trade.Price, position.val AS Position from Fireball_Reporting..Trade CROSS APPLY ( SELECT case when (Buy = 1 and Long = 1) then 1 when (Buy = 0 and Long = 0) then 1 else 0 end AS val ) AS position where porfolioid = 5 AND position.val = 1


5
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.