SQL Server:使用XML的SubQuery中的列名无效

时间:2016-12-05 20:05:22

标签: sql sql-server tsql

我有以下查询,其子查询为我提供了Categories列。当我尝试添加WHERE子句时,出现Invalid column name 'Categories'错误。

SELECT 
    l.LID, 
    Company, 
    Doors, 
    City, 
    Region, 
    Country, 
    Categories = STUFF((
            SELECT 
                CONVERT(varchar(100), Junc_CatID) + ', ' 
            FROM BND_ListingJunction_testing j 
            WHERE j.Junc_LID = l.LID 
            FOR XML PATH('')), 1, 2, '')
FROM BND_Listing_testing l
--FILTERS
WHERE 
    (Categories = '[querystring:filter-Category]' or '[querystring:filter-Category]'='All')
GROUP BY 
    LID, 
    Company, 
    Doors, 
    City, 
    Region, 
    Country

1 个答案:

答案 0 :(得分:1)

如果刚刚创建,则无法使用已创建的列。

例如,这是错误的,因为税收不存在

SELECT 
    id, 
    sales, 
    sales * tax as taxes
FROM sales
WHERE 
    taxes > 100

所以你需要我们一个子查询或重复代码。

SELECT *
FROM (SELECT id, sales, sales * tax as taxes FROM sales) T
WHERE 
    T.taxes > 100

OR

SELECT 
    id, 
    sales, sales * tax as taxes
FROM sales
WHERE 
    sales * tax > 100