Monday, May 10, 2010

SQL Server | Top N + Union + Random (derived tables)

select *
from (select top 1 Content, ID, Picture, Title, SubTitle
from HeaderBannerJQ_Slides
where Content=1
order by newid()) as res
union all
select *
from (select top 1 Content, ID, Picture, Title, SubTitle
from HeaderBannerJQ_Slides
where Content=2
order by newid()) as res
union all
select *
from (select top 1 Content, ID, Picture, Title, SubTitle
from HeaderBannerJQ_Slides
where Content=3
order by newid()) as res

Resource: http://sqlblogcasts.com/blogs/tonyrogerson/archive/2007/05/18/using-top-and-order-by-with-union-union-all.aspx

No comments:

Post a Comment