2010-01-19 108 views
9

是否有TSQL办法做到像这样使用的一个派生选择列:TSQL Where子句

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中有一个技巧使用“拥有d = 6”)。

回答

18
select a,b,c FROM(
select a,b,c, 
case 
    when a=1 then 5 
    when a=2 then 6 
end as d 
from some_table 
) AS t 
where d=6 
+0

谢谢,亚历克斯 – 2010-10-14 01:56:32

2

让您发布查询子查询,其中d = 6,据我所知是没有办法在同一个查询引用派生列从中选择。

4

这是使用CTEs的好地方,例如:

WITH MassagedData (a, b, c, d) AS 
(
    select a, b, c, 
     case 
      when a=1 then 5 
      when a=2 then 6 
     end as d 
    from some_table 
) 

SELECT a,b,c 
FROM MassagedData 
where d=6 
+0

愿望这是upvoted更因为它比接受的答案嘈杂少得多(spasibo!)。 – MushinNoShin 2015-07-23 17:42:51

2

我打算在这一个与AlexKuznetsov同意,但我也想补充一点,如果您的查询是(不管多少复杂)限制在CASE中存在的WHERE子句的情况下,那么这些CASE将永远不会被返回,因此不应该首先被选中。

例如,你设置d到“6”,其中a是“2”,然后限制WHERE d = 6,所以你可以改为做:

SELECT a,b,c, 
    6 AS d 
FROM some_table 
WHERE a = 2 

这将返回更相同的结果优化和干净的时尚。这就是为什么恕我直言,能够引用派生列没有意义。

1

另一种选择是实现您的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 
0

的另一种方法,这是用CROSS APPLY

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