1

I have an sql query like this

Select col1, (select abc from table2 where def=1) as col2
From Table1 inner join table3 on Table1.id = table3.id
Where col2 = 4

The problem is that the where condition doesn't work. I get an error saying

Invalid column name 'col2'

Kindly help me fix this sql query.

Thanks in advance

1
  • 1
    Is that your actual query? Seems odd. The sub query isn't correlated. Commented Feb 2, 2012 at 16:05

2 Answers 2

4

You can define it in a CROSS APPLY and then reference in the SELECT and WHERE

SELECT col1,
       col2
FROM   Table1
       INNER JOIN table3
         ON Table1.id = table3.id
       CROSS APPLY (SELECT abc
                    FROM   table2
                    WHERE  def = 1) C(col2)
WHERE  col2 = 4  
Sign up to request clarification or add additional context in comments.

3 Comments

@ypercube - Yes. I was thinking that there would be a difference if the sub query could return 0 rows rather than 1 (and that maybe I should use OUTER APPLY instead) but the WHERE clause takes care of that.
@MartinSmith - Thanks. Can I use multiple queries in CROSS APPLY? What if I need a col3 similar to col2.
@Derin - The SELECT in the CROSS APPLY can return multiple columns and you can have multiple levels of CROSS APPLY. If you were to show your actual query there may well be simpler or more efficient ways though.
0

Using a CTE (Common Table Expression):

WITH SubQuery AS (Col2) {
    SELECT 
        ABC
    FROM
        table2
    WHERE
        def = 1
}
SELECT
    T.Col1,
    S.Col2
FROM
    SubQuery S,
    Table1 T
    INNER JOIN table3 t3
        ON T.id = t3.id
WHERE
    S.Col2 = 4

Although I must say I agree with the first comment - this makes no sense since your subquery is not correlated (joined) to the rest of your query...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.