简体   繁体   中英

How do I add a field/column from a subquery into the outer select statement?

I'm new to SQL and have been learning on my own for a couple of months.

I have a subquery with multiple joins. The where clause in the subquery is for one of the joins and I have added that field/column to my outer select statement with no issues. My problem is, I need to include a field/column from one of the other joins in the subquery. How do I do that? Just adding it to the outer select statement gives a "could not be bound" error.

Here is my subquery:

(select cn.UniqContactName 
 from ContactName cn
 join ContactNumber cnu on cn.UniqContactName = cnu.UniqContactName
 join ContactClass cc on cn.UniqContactName = cc.UniqContactName
 join LkContactClass lkcc on lkcc.UniqLkContactClass = cc.UniqLkContactClass
 join ConfigureLkLanguageResource lr on lr.ConfigureLkLanguageResourceID = lkcc.ConfigureLkLanguageResourceID and lr.CultureCode = 'en-US'

 where lr.ResourceText like '%Opt Out - Electronic Communication%'
 )

I want to add a field/column from the ContactNumber table to my outer select statement.

you can change subquery to outer apply in my opinion.

like:

select .....
from ....
OUTER APPLY (select cn.UniqContactName 
 from ContactName cn
 join ContactNumber cnu on cn.UniqContactName = cnu.UniqContactName
 join ContactClass cc on cn.UniqContactName = cc.UniqContactName
 join LkContactClass lkcc on lkcc.UniqLkContactClass = cc.UniqLkContactClass
 join ConfigureLkLanguageResource lr on lr.ConfigureLkLanguageResourceID = lkcc.ConfigureLkLanguageResourceID and lr.CultureCode = 'en-US'

 where lr.ResourceText like '%Opt Out - Electronic Communication%'
 ) as OA

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