2

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

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

正如现在所写的那样,我得到一个invalid column name 'foo'错误。无论如何,选择语句可以用作视图吗?

4

4 回答 4

2

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

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

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

于 2010-07-06T16:14:16.767 回答
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]
于 2010-07-06T16:14:00.587 回答
1
WITH TmpTbl as (SELECT 'blah' as foo)
SELECT foo, CASE WHEN foo='blah' THEN 'fizz' 
            ELSE 'buzz' 
            END as bar FROM TmpTbl
于 2010-07-06T16:17:22.967 回答
0

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

select a.foo,
  case when a.foo = 'blah'
  then 'fizz'
  else 'buzz'
  end as bar
from (select 'blah' as foo) a
于 2010-07-06T16:15:55.623 回答