tags:

views:

96

answers:

4

Here is my query:

    Select Top 10 CS.CaseStudyID,
    CS.Title,
    CSI.ImageFileName
From CaseStudy CS
Left Join CaseStudyImage CSI On CS.CaseStudyID = CSI.CaseStudyID
And CSI.CSImageID in(
    Select Min(CSImageID) -- >not really satisfactory
    From CaseStudyImage
    Group By CaseStudyID
    )
Order By CS.CaseStudyID ASC

Instead of min(CSImageID) I'd like a random record from my CaseStudyImage table that corresponds to the particular case study

Can anyone point me in the right direction pleas?

A: 

ORDER BY RAND() LIMIT 1?

Bombe
No Limit in T-SQL or rand (there's newid()) and I'm geting lost combining the equivalent Top with order by newid()
Allen Hardy
Sorry there is Rand but its not helping me yet
Allen Hardy
A: 

This article describes 3 techniques for random sampling in t-sql. It depends on how much control you have over your table structure one of them might do want you want.

Vincent Ramdhanie
+1  A: 

You can use ranking function and newid() to create randomize order with grouping.

WITH CSI AS (
    SELECT CSI.CaseStudyID, CSI.ImageFileName,
     ROW_NUMBER() OVER(PARTITION BY CSI.CaseStudyID ORDER BY newid()) AS RowNumber
    FROM CaseStudyImage CSI
)
SELECT TOP (10) CS.CaseStudyID, CS.Title, CSI.ImageFileName
FROM CaseStudy CS LEFT JOIN CSI On CS.CaseStudyID = CSI.CaseStudyID
WHERE CSI.RowNumber = 1
ORDER BY CS.CaseStudyID ASC
chaowman
+1  A: 

usually, just ORDER BY NEWID() does the trick

gbn