Home > Net >  How to select N random groups within a table
How to select N random groups within a table

Time:12-08

My groups are split across rows like so:

   Row  Group
   1    A
   2    A
   3    A
   4    B
   5    B
   6    C
   7    C
   8    C
   9    C

How can I select all rows for any 2 randomly chosen groups?

CodePudding user response:

To select rows of any two groups

select * 
from t_groups
group by Group
having Group in ['A', 'B']; 

To randomly select any two groups

select * 
from t_groups
group by Group
having Group in (
SELECT Group FROM t_groups
ORDER BY RAND()
LIMIT 2); 

CodePudding user response:

Sort random, pick 2 groups.

SELECT *
FROM your_table AS t
WHERE `Group` IN (
  SELECT `Group` FROM (
    SELECT `Group`
      FROM your_table
      GROUP BY `Group`
      ORDER BY RAND()
      LIMIT 2) q);

db<>fiddle here

  • Related