how to use sub query which has from clause from other tables?

Muhammad Kashan Khan 1 Reputation point
2020-10-14T06:38:34.847+00:00

Hello there?

I have a Query which has multiple sub Queries, but there is a problem using a sub query where i am using from clause like below:

(select sum(total) from (select sum(total) from table_1 where id =2) as tbltemp)).

How can i use above query in sub queries, it is returning syntax error.

Please guide!

Thanks in advance.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,516 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Olaf Helper 38,861 Reputation points
    2020-10-14T06:43:32.31+00:00

    The outer brackets are wrong, remove them.
    And it don't make much sense to use a sub query here, the inner query returns the same as the outer with the sub query =>

    select sum(total) 
    from table_1 
    where id =2
    
    2 people found this answer helpful.
    0 comments No comments

  2. EchoLiu-MSFT 14,571 Reputation points
    2020-10-14T06:41:55.477+00:00

    Hi @Muhammad Kashan Khan

    The column in the table expression must be aliased.Please refer to:

        (select sum(total) from (select sum(total) total from table_1 where id =2) tbltemp)  
    

    The above select statement adds parentheses. Considering that you publish in this format, it may be a partial subquery. If it is a single statement, parentheses are not required:

        select sum(total) from (select sum(total) total from table_1 where id =2) tbltemp  
    

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments