Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...I love this site! It's so nice to know that there are so many people out there who are willing to share their knowledge..."

Geography

Where in the world do Tek-Tips members come from?

T-SQL to Generate A random record and type per person

rosherguy (Programmer)
14 May 12 10:29
I have a problem that I have built a sort of solution to which seems to work in 99% of cases but I am sure there must be an easier solution to this.

I have a table with a load of records of differing types (they are types of sales with a sales identifier number). What I need to do is to select for each person in a given period a random type of sale with the identifier in week 1 then in week 2 try to select a different type unless all that perosn has sold is the same type as week 1.

My current solution involves row_number and then selections based on where exists and not exists. Does anyone know if there is a much easier solution to do this?
markros (Programmer)
14 May 12 18:07
I think you need to create an inline (or table-valued) function called GetRandomTypes. This function will accept PersonID parameter and it will be something like

select type, row_number() over (order by @PersonID * checksum(NewID()) as Rn from SalesTypes -- I added @PersonID here just so the function will use this parameter (we don't really need it)

Then your main select will be

CODE

select P.* cross apply dbo.GetRandomTypes(P.PersonID) F where P.WeekNumber = F.Rn -- so each week will get a different value

PluralSight Learning Library

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close