生成的列依赖于其他生成的列

时间:2010-07-06 16:11:12

标签: sql sql-server select calculated-columns

这样做的最佳方法是什么?

select 'blah' as foo,
        CASE 
          WHEN foo='blah' THEN 'fizz'
          ELSE 'buzz'
        END as bar

正如现在所写,我收到了invalid column name 'foo'错误。无论如何都可以将select语句用作视图吗?

4 个答案:

答案 0 :(得分:2)

你需要使用这样的嵌套选择:

select foo,
  case when foo='blah'
  then 'fizz'
  else 'buzz'
  end as bar
from ( select 'blah' as foo ) a

问题是在同一个select语句中名称不能识别列foo。

答案 1 :(得分:1)

如果您不想重复列定义,可以使用派生表。

select   case when foo='blah'
  then 'fizz'
  else 'buzz' 
end as bar
FROM
(
select 'blah' as foo
) derived

或CTE

;
With blahs As
(
select 'blah' as foo
)


select   case when foo='blah'
  then 'fizz'
  else 'buzz' 
end as bar
FROM blahs

快速测试显示以下所有三个版本的执行计划是相同的

SELECT foo,
       CASE
              WHEN foo='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   ( SELECT
               CASE
                       WHEN [number] % 5 = 0
                       THEN 'blah'
                       ELSE 'notblah'
               END AS foo
       FROM    [master].[dbo].[spt_values]
       )
       D ;


WITH blahs AS
     ( SELECT
             CASE
                     WHEN [number] % 5 = 0
                     THEN 'blah'
                     ELSE 'notblah'
             END AS foo
     FROM    [master].[dbo].[spt_values]
     )
SELECT foo,
       CASE
              WHEN foo='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   blahs


SELECT
       CASE
              WHEN [number] % 5 = 0
              THEN 'blah'
              ELSE 'notblah'
       END AS foo,
       CASE
              WHEN
                     CASE
                            WHEN [number] % 5 = 0
                            THEN 'blah'
                            ELSE 'notblah'
                     END='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   [master].[dbo].[spt_values]

答案 2 :(得分:1)

WITH TmpTbl as (SELECT 'blah' as foo)
SELECT foo, CASE WHEN foo='blah' THEN 'fizz' 
            ELSE 'buzz' 
            END as bar FROM TmpTbl

答案 3 :(得分:0)

您可以像这样使用表查询:

select a.foo,
  case when a.foo = 'blah'
  then 'fizz'
  else 'buzz'
  end as bar
from (select 'blah' as foo) a