mardi 12 janvier 2021

repeatable sample by group (not rows) using rand() sql

For retailing data, it is often user-based and users buy multiple occasions. We need to randomly sample users (not by each purchase record/row) and hope to reproduce the results later on or join the same user samples for other tables.

For example, we wish to draw some users from a promotion period but even if I set the seed in rand(), I keep getting different samples each time I run.

    SELECT user_id FROM 
           (SELECT DISTINCT user_id 
           FROM table1 
           WHERE day_id >= "2009-01-09" AND day_id < "2011-02-16"
           ) u 
     ORDER BY RAND(200) LIMIT 100



Aucun commentaire:

Enregistrer un commentaire