Query to get row from one table, else random row from another

Posted by Jimmy on Stack Overflow See other posts from Stack Overflow or by Jimmy
Published on 2010-03-25T14:35:04Z Indexed on 2010/03/25 14:53 UTC
Read the original article Hit count: 163

Filed under:

tblUserProfile - I have a table which holds all the Profile Info (too many fields)

tblMonthlyProfiles - Another table which has just the ProfileID in it (the idea is that this table holds 2 profileids which sometimes become monthly profiles (on selection))

Now when I need to show monthly profiles, I simply do a select from this tblMonthlyProfiles and Join with tblUserProfile to get all valid info.

If there are no rows in tblMonthlyProfile, then monthly profile section is not displayed.

Now the requirement is to ALWAYS show Monthly Profiles. If there are no rows in monthlyProfiles, it should pick up 2 random profiles from tblUserProfile. If there is only one row in monthlyProfiles, it should pick up only one random row from tblUserProfile.

What is the best way to do all this in one single query ?

I thought something like this

select top 2 * from tblUserProfile P LEFT OUTER JOIN tblMonthlyProfiles M on M.profileid = P.profileid ORder by NEWID()

But this always gives me 2 random rows from tblProfile. How can I solve this ?

© Stack Overflow or respective owner

Related posts about tsql