SQL Server having criteria for subquery
-
08-12-2019 - |
Question
My query looks like this,
SELECT field1, field2, (SELECT TOP 1 field1 from table1) as field3
FROM table2
HAVING field3 > 0
it throws an error
invalid column name field3
Solution
Don't use a HAVING
. A WHERE
is more appropriate here.
SELECT field1, field2, (SELECT TOP 1 field1 from table1) as field3
FROM table2
WHERE (SELECT TOP 1 field1 from table1) > 0
Now, I am assuming that you have some work of WHERE
on the sub query. That uses values from table2. Otherwise, pull that query out and assign the value to a variable.
DECLARE @field3 AS INT --change this to the correct data type
SELECT TOP 1 @field3 = field1
FROM table1
SELECT field1, field2, @field3 as field3
FROM table2
WHERE @field3 > 0
Now, only do this if you need to return empty result set. If you don't need the empty result set, we can exclude the query all together.
DECLARE @field3 AS INT --change this to the correct data type
SELECT TOP 1 @field3 = field1
FROM table1
IF @field3 > 0
BEGIN
SELECT field1, field2, @field3 as field3
FROM table2
END
OTHER TIPS
It is not possible to use data item aliases within HAVING
or WHERE
.
You need to re-call the value within the HAVING
statement. However, using a WHERE
clause would be better suited here:
WHERE (SELECT TOP 1 field1 from table1) > 0
Change the HAVING to fully define field3 again. ie:
SELECT field1, field2, (SELECT TOP 1 field1 from table1) as field3
FROM table2
HAVING (SELECT TOP 1 field1 from table1) > 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow