Avatar of nhmedia
nhmedia

asked on 

How to write a sub query with multiple conditions

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?
Microsoft SQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
nhmedia

8/22/2022 - Mon