简体   繁体   中英

SQL Subquery Syntax Error Near ')' — Not missing alias

I have a similar problem to this one , but the solution in that case was to add an alias to the subquery. In my case, each of my subqueries has an alias, but I'm getting the message Incorrect syntax near ')' at the end of each of my subqueries.

I'm writing the query in 2008 R2 but targeting SSRS 2000

My entire query is fairly long, but here's a shortened pseudo-code version:

SELECT  A
       ,B
       ,C
       ,D
       ,E

FROM
     (
       SELECT A as 'A', B as 'B', id
       FROM table t
       WHERE A = 'some value'
       GROUP BY A, B
     ) AS sub1

LEFT JOIN 
     (
       SELECT C as 'C', D as 'D', id
       FROM 
            (
               SELECT id
               FROM nutherTable
               WHERE id IN
               (
                   SELECT DISTINCT id
                   FROM sub1
               )
            )
       WHERE D like '%param%'
     ) AS sub2

    ON sub2.id = sub1.id

LEFT JOIN
     (
       SELECT E as 'E', id
       FROM finalTable
       WHERE E IS NOT NULL
     ) AS sub3

     ON sub3.id = sub2.id

You'll notice that in the first LEFT JOIN , the join uses a subquery, and the FROM and WHERE clauses within that subquery also use subqueries. In my actual query, both LEFT JOINs have this same structure. One of the things I don't understand is that the nested subqueries don't require an alias. If I try to use an alias with the nested clauses, I get an error. So it's only having trouble with the outer queries in the LEFT JOINs .

I've read in other posts that subqueries can only return results for a single field, but I've seen many example where multiple fields are returned from a subquery, so I don't think that's the problem here. Or if that's going to be a problem, the error will be different. Everything I've read attributes this problem to lacking an alias for the subquery, and I get the same results with or without an alias (no alias at all, as well as using AS and not using AS ).

You need to provide a table alias for every subquery you're using as a result set:

LEFT JOIN 
     (
       SELECT C as 'C', D as 'D', id
       FROM 
            (
               SELECT id
               FROM nutherTable
               WHERE id IN
               (
                   SELECT DISTINCT id
                   FROM sub1
               )
            ) SomeTableName -- HERE IS THE PROBLEM
       WHERE D like '%param%'
     ) AS sub2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM