Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

SQL Correlated Subquery in SELECT clause

Avatar of pzozulka
pzozulka asked on
Microsoft SQL ServerMicrosoft SQL Server 2008SQL
10 Comments1 Solution601 ViewsLast Modified:
I have a query that returns the following data:

Name            Age      Phone
John Smith    40        555-5555
John Smith    40        222-2222

I want it to only return a single row, because this is causing us to have duplicates in the report.
Current Query
Select Contact.Name, Contact.Age, ContactInfo.Phone
From Contact left join ContactInfo on Contact.Id = ContactInfo.Id

New Query
Select Contact.Name, Contact.Age, 
 ( Select TOP 1 CI.Phone
   From ContactInfo CI left join Contact C ON C.Id = CI.Id
   Where C.Id = Contact.Id
   Order By CI.Phone ASC
 ) as Phone
From Contact left join ContactInfo on Contact.Id = ContactInfo.Id

Is there anything you see wrong with the correlated subquery? It's giving me an error message:

Column 'Contact.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.