如何让它工作,它没有Where子句,否则使用Where子句,我得到明显的错误,但基本上需要做什么,谁知道如何处理这个?
select ID,
Name,
case T.N
when 1 then City1
when 2 then City2
when 3 then City3
end as City,
case T.N
when 1 then State1
when 2 then State2
when 3 then State3
end as State
from YourTable
cross join (values(1),(2),(3)) as T(N)
Where City is NOT Null
答案 0 :(得分:22)
您不能在WHERE子句中使用别名。要么重复表达式(杂乱),要么将SELECT放在子查询中,然后将WHERE子句放在外部查询中:
SELECT Id, Name, City, State
FROM
(
SELECT
ID,
Name,
CASE T.N
WHEN 1 THEN City1
WHEN 2 THEN City2
WHEN 3 THEN City3
END AS City,
CASE T.N
WHEN 1 THEN State1
WHEN 2 THEN State2
WHEN 3 THEN State3
END AS State
FROM YourTable
CROSS JOIN (VALUES(1),(2),(3)) AS T(N)
) T1
WHERE City IS NOT NULL
答案 1 :(得分:9)
您不能在SELECT
子句中使用别名(来自WHERE
子句),因为logical processing order(部分:Logical Processing Order of the SELECT statement
)是WHERE
然后SELECT
:
FROM
ON
JOIN
WHERE <--
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT <--
DISTINCT
ORDER BY <--
TOP
但是,您可以在ORDER BY
中使用别名:
SELECT h.SalesOrderID, YEAR(h.OrderDate) OrderYear
FROM Sales.SalesOrderHeader h
ORDER BY OrderYear;
解决方案:请参阅Mark Byers提供的解决方案。