我正在使用SQL Server 2008 R2。我希望在派生的列上有一个WHERE子句。
我有这样的事情:
SELECT ActualColumn1,
CASE WHEN condition THEN value1 ELSE value2 AS DerivedColumn1
FROM
...
WHERE
DerivedColumn1 <> 'Foo' -- I'd like to filter on the derived column
运行此查询会报告错误&#34;无效的列名DerivedColumn1&#34;。
答案 0 :(得分:3)
您无法直接引用WHERE
中的别名(可以<{1}} ),您必须使用子查询或CTE(或重复ORDER BY
中的CASE WHEN
:
WHERE
答案 1 :(得分:2)
虽然您无法直接使用派生列,但您可以通过多种方式获得所需的结果:
WHERE
子句中过滤内部选择的列。以下是最后一种方法的说明:
WITH CTE (ActualColumn1, DerivedColumn1)
AS
(
SELECT ActualColumn1,
CASE WHEN condition THEN value1 ELSE value2 AS DerivedColumn1
FROM ...
)
SELECT ActualColumn1, DerivedColumn1
FROM CTE
WHERE DerivedColumn = ...
答案 2 :(得分:1)
答案 3 :(得分:1)
SELECT * FROM (
SELECT ActualColumn1,
CASE WHEN condition THEN value1 ELSE value2 AS DerivedColumn1
FROM
...
) Z
WHERE
DerivedColumn1 <> 'Foo'
注意:强> 如果您使用子查询,将 ALIAS 名称提供给子查询必须,如上所示 - Z ,否则将引发错误。
答案 4 :(得分:0)
你不能直接使用它,但你可以这样做:
select * from
(
SELECT ActualColumn1,
CASE WHEN condition THEN value1 ELSE value2 AS DerivedColumn1
FROM
...
)
WHERE
DerivedColumn1 <> 'Foo' -- I'd like to filter on the derived column
答案 5 :(得分:0)
您还可以使用CROSS APPLY
SELECT tbl.ActualColumn1, cap.DerivedColumn1
FROM ... as tbl
CROSS APPLY (SELECT CASE WHEN condition THEN value1 ELSE value2 END) AS cap(DerivedColumn1)
WHERE cap.DerivedColumn1 <> 'Foo'