Select random row for each group

前端 未结 2 1645
死守一世寂寞
死守一世寂寞 2020-12-09 21:53

I have a table like this

ID    ATTRIBUTE
 1    A
 1    A
 1    B
 1    C
 2    B
 2    C
 2    C
 3    A
 3    B
 3    C

I\'d like to selec

相关标签:
2条回答
  • 2020-12-09 22:15

    Put a big random number in front of each record (id) and choose within each group the record with the lowest random number.

    $ cat test.txt
    \N  1   a
    \N  2   b
    \N  2   c
    \N  2   d
    \N  3   e
    \N  4   f
    
    
    $ mysql
    
    USE test;
    DROP TABLE test;
    CREATE TABLE test (id0 INT NOT NULL AUTO_INCREMENT, id VARCHAR(1),  attribute VARCHAR(1), PRIMARY KEY (id0));
    LOAD DATA LOCAL INFILE '~/mysql/test.txt' INTO TABLE test FIELDS TERMINATED BY '\t';
    
    DROP TABLE rtest;
    CREATE TABLE rtest (random INT(8), id0 VARCHAR(1), id VARCHAR(1),  attribute VARCHAR(1),  PRIMARY KEY (id, random));
    
    INSERT INTO rtest
    SELECT CAST(1000000. * rand() AS INT) AS random, test.* FROM test;
    
    SELECT rtest.* FROM rtest,
    (SELECT id, min(random) AS random FROM rtest GROUP BY id) AS sample WHERE rtest.random=sample.random AND rtest.id=sample.id;
    
    0 讨论(0)
  • 2020-12-09 22:40
    select distinct on (id) id, attribute
    from like_this
    order by id, random()
    

    If you only need the attribute column:

    select distinct on (id) attribute
    from like_this
    order by id, random()
    

    Notice that you still need to order by id first as it is a column of the distinct on.

    If you only want the distinct attributes:

    select distinct attribute
    from (
        select distinct on (id) attribute
        from like_this
        order by id, random()
    ) s
    
    0 讨论(0)
提交回复
热议问题