Selecting n random rows from a table for each unique customer

Viewed 22

I'm wondering if this is possible. Using the rand() function I can select random rows, however is it possible to select say 120 random rows and group by each customer, because I want 100 rows of data for each unique person. In addition is it possible to go one further level down and select 10 random rows for each month, for each customer?

1 Answers

You can use the RAND function inside an ORDER BY clause, then limit the amount of rows you need with the LIMIT clause.

SELECT * 
FROM tab
ORDER BY RAND(45)
LIMIT 4

Check the demo here.

Note 1: If you want to have always the same customers, then you can use a seed inside the RAND function.

Note 2: I wouldn't recommend this approach for large datasets, as it is quite expensive.

Related