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)
不能在WHERE,GROUP BY或HAVING子句中使用
。与MySQL doc类似,它说:
标准SQL 不允许在WHERE子句中引用列别名
但是在中,您可以使用一些trick to overcome thisMySQL
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