简体   繁体   中英

SQL Server: how to select sub-query column in main query

I have a query to select particular day-time for a office.

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

I need to select the sub-query column officeid in main query. Above query throws a syntax error.

Thanks for the help.

You can't use officied column from subquery not only because that subquery select list doesn't contain this column, but also bu the reason it is in where condition, not in some join/apply.

Instead you can join that subquery and use it columns like this:

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'

or (even simplier and more natural):

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

You can use inner join:

select a.sat_date ,b.officied
 from OfficeHours a inner join office b on(a.officeik=b.OfficeIK)
  where a.sat_date = '9:30 AM' and b.officeid=50000

You can use INNER JOIN , if you want to use sub-query, you can try this:

select a.sat_date, 50000 AS officeid
from OfficeHours a
where sat_date = '9:30 AM'
   and officeik in
   (select OfficeIK from office where officeid = 50000)

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