Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL SELECT PROBLEM

Author  Topic 

RichardSteele
Posting Yak Master

160 Posts

Posted - 2011-04-19 : 13:57:27
I have a sql statement that returns the top 15 portfolios most recently published by a group of photographers. However some photographers have more than one portfolio. I only want to show a randomized selection of 5 portfolios by 5 DIFFERENT people. How do I modify this statement so that it doesn't duplicate people? Thanks in advance.

SELECT DISTINCT TOP 15 G.Lastname as Lastname, G.SubDirectory as SubDirectory, G.Firstname as Firstname, G.Gallery as Gallery, G.Custnumber as Custnumber, I.ImageNumber as Imagenumber, I.ImagePosition as ImagePosition, I.RecordNo, I.ImageSizeList, I.GeneralRandomNo as GeneralRandomNo, p.ImgQty as ImageQTy, P.Subdirectory as Portfolio, P.DateTime as DateTime, p.ExhibitionOpened, P.RandomNo, P.AutoID as AutoID, I.PortfolioName, newid() as RandID
FROM ArtistSetup G INNER JOIN
ArtistPortfolios P ON G.Custnumber = P.Custnumber INNER JOIN
ArtistIndividualWorks I ON P.SubDirectory = I.PortfolioName AND I.Custnumber = G.Custnumber
WHERE P.ImgQty>0 AND G.Gallery='PhotoBistro' and I.ImagePosition=1 and P.ShowcaseOK=1
ORDER BY p.ExhibitionOpened desc

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-04-19 : 14:41:04
One way to pick 5 distinct photographers is to use the row_number function as follows:

SELECT * FROM
(

SELECT DISTINCT TOP 15 G.Lastname as Lastname,
G.SubDirectory as SubDirectory, G.Firstname as Firstname,
G.Gallery as Gallery, G.Custnumber as Custnumber,
I.ImageNumber as Imagenumber, I.ImagePosition as ImagePosition,
I.RecordNo, I.ImageSizeList, I.GeneralRandomNo as GeneralRandomNo,
p.ImgQty as ImageQTy, P.Subdirectory as Portfolio,
P.DateTime as DateTime, p.ExhibitionOpened, P.RandomNo,
P.AutoID as AutoID, I.PortfolioName, newid() as RandID,
ROW_NUMBER() OVER (PARTITION BY G.Lastname, G.FirstName ORDER BY NEWID()) AS RN

FROM ArtistSetup G INNER JOIN
ArtistPortfolios P ON G.Custnumber = P.Custnumber INNER JOIN
ArtistIndividualWorks I ON P.SubDirectory = I.PortfolioName AND I.Custnumber = G.Custnumber
WHERE P.ImgQty>0 AND G.Gallery='PhotoBistro' and I.ImagePosition=1 and P.ShowcaseOK=1
) R
where RN = 1
Order by ExhibitionOpened desc
You have to be on SQL 2005 or higher to do it this way.
Go to Top of Page
   

- Advertisement -