2

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.

3
  • 1
    not defined alias a and what's the error you are getting? Commented Dec 10, 2015 at 7:49
  • I think b.officied -> b.officeid Commented Dec 10, 2015 at 7:49
  • I have edited the questions. thanks for pointing out Commented Dec 10, 2015 at 7:51

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the solution. but clear on the point "subquery select list doesn't contain this column". I am selecting all the columns in the subquery table
@bmsqldev your subquery is (select OfficeIK from office... and not (select OfficeIK, officeid from office, so even if it was in join - you can't use column you're not included into select list since it will not be present in query result
1

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

Comments

1

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)

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.