TSQL-在Where子句中使用派生的Select列
TSQL中是否有一种方法可以执行以下操作:TSQL-在Where子句中使用派生的Select列,sql,sql-server,sql-server-2005,tsql,case,Sql,Sql Server,Sql Server 2005,Tsql,Case,TSQL中是否有一种方法可以执行以下操作: select a,b,c, case when a=1 then 5 when a=2 then 6 end as d from some_table where d=6 实际的case语句非常复杂,所以我尽量避免在where子句中重复它?有什么诀窍可以做到这一点吗 (我认为MySQL中有一个使用“having d=6”的技巧。)将发布的查询作为子查询,并从中选择d=6。据我所知,无法在同一查询中引用派生列。这是一个很好的使用场所,例如:
select a,b,c,
case
when a=1 then 5
when a=2 then 6
end as d
from some_table
where d=6
实际的case语句非常复杂,所以我尽量避免在where子句中重复它?有什么诀窍可以做到这一点吗
(我认为MySQL中有一个使用“having d=6”的技巧。)将发布的查询作为子查询,并从中选择d=6。据我所知,无法在同一查询中引用派生列。这是一个很好的使用场所,例如: 我同意这一点,但我还要补充一点,如果您的查询(无论多么复杂)限制在
案例中存在的WHERE
子句案例中,那么这些案例将永远不会返回,并且不应该首先被选择
例如,您将d
设置为“6”,其中a
为“2”,然后限制为其中d=6
,因此您可以改为:
SELECT a,b,c,
6 AS d
FROM some_table
WHERE a = 2
这将以更加优化和干净的方式返回相同的结果。这就是为什么,IMHO,能够引用派生列没有意义。另一个选项是将case
语句作为函数实现。特别适用于转换或计算问题。函数的好处在于“业务”逻辑位于一个位置,可以轻松地在其他查询中重用
-- sample code not tested
CREATE FUNCTION dbo.fn_MyConvertA(
-- Add the parameters for the function here
@a int
)
RETURNS int -- for example
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar as int
-- Add the T-SQL statements to compute the return value here
set @ResultVar = case when @a = 1 then 5 when @a = 2 then 6 else 10 end
-- Return the result of the function
RETURN @ResultVar
END
GO
-- now you case write your query
select a,b,c, dbo.fn_MyConvertA(a) as d
from some_table
where dbo.fn_MyConvertA(a)=6
另一种方法是使用交叉应用:
select a,b,c,
from some_table
CROSS APPLY (SELECT case
when a=1 then 5
when a=2 then 6
end) CxA(d)
where d=6
希望这是更高的投票,因为它的噪音远远低于公认的答案。
-- sample code not tested
CREATE FUNCTION dbo.fn_MyConvertA(
-- Add the parameters for the function here
@a int
)
RETURNS int -- for example
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar as int
-- Add the T-SQL statements to compute the return value here
set @ResultVar = case when @a = 1 then 5 when @a = 2 then 6 else 10 end
-- Return the result of the function
RETURN @ResultVar
END
GO
-- now you case write your query
select a,b,c, dbo.fn_MyConvertA(a) as d
from some_table
where dbo.fn_MyConvertA(a)=6
select a,b,c,
from some_table
CROSS APPLY (SELECT case
when a=1 then 5
when a=2 then 6
end) CxA(d)
where d=6