SQL Server:如何在主查询中选择子查询列

bms*_*dev 1 sql t-sql sql-server

我有一个查询来选择办公室的特定白天时间。

select 
    a.sat_date, 
    b.officeid 
from  
    OfficeHours a 
where 
    sat_date = '9:30 AM'
    and officeik in (select OfficeIK from office where officeid = 50000) b
Run Code Online (Sandbox Code Playgroud)

我需要officeid在主查询中选择子查询列。上面的查询抛出一个syntax error.

谢谢您的帮助。

And*_*yev 5

您不能使用officied子查询中的列,不仅因为该子查询选择列表不包含此列,而且还因为它处于 where 条件中,而不是在某些 join/apply 中。

相反,您可以加入该子查询并使用它的列,如下所示:

select 
    a.sat_date,
    b.officied 
from OfficeHours as a
    inner join (select * from office where officeid = 50000) as b on b.officeik = a.officeik
where a.sat_date = '9:30 AM'
Run Code Online (Sandbox Code Playgroud)

或(甚至更简单、更自然):

select 
    a.sat_date,
    b.officied 
from OfficeHours as a
    inner join office as b on b.officeik = a.officeik
where 
    a.sat_date = '9:30 AM'
    and b.officeid = 50000
Run Code Online (Sandbox Code Playgroud)