We help IT Professionals succeed at work.
Get Started

How to write a sub query with multiple conditions

352 Views
Last Modified: 2012-05-11
I have an SQL view containing many hundreds of pieces of content
And I have a table that has a record for every time those items have been viewed on a website.
I now need to extract the 20 most popular items
I have written a sub query to get the 20 most commonly viewed items:
SELECT top 20 ContentID , COUNT(ContentID) AS ID FROM  table1 (nolock) where SiteID = 26 and ContentID not in (0,-1)
 and UserAgent not like '%bot%' and  date='2011-05-16' GROUP BY  ContentID order by ID desc

But when I try something like this:
Select  * from View1 where ContentID in (SELECT top 20 ContentID , COUNT(ContentID) AS ID FROM  table1 (nolock) where SiteID = 26 and ContentID not in (0,-1)
 and UserAgent not like '%bot%' and  date='2011-05-16' GROUP BY  ContentID order by ID desc)

I get an error

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

Could anyone suggest how I can structure this to query to get what I need?
Comment
Watch Question
Software Engineer
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
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:

  • Troubleshooting
  • Research
  • Professional Opinions
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