2

我似乎无法理解这一点。我在 SQlite 中有一个表,我需要从中random()为每个组选择一条记录。因此,考虑如下表:

id         link       chunk

2           a           me1

3           b           me1

4           c           me1

5           d           you2

6           e           you2

7           f           you2

我需要为每个块返回一个随机链接值的 sql。所以有一次我运行它会给出:

me1    |   a
you2   |   f

下次也许

me1    |   c
you2   |   d

我知道已经回答了类似的问题,但我没有找到适用于此处的推导。

更新:

坚果,跟进问题:所以现在我需要排除新字段“qcinfo”设置为“Y”的行。

当然,这会在随机 ID 达到 qcinfo = 'Y' 的位置时隐藏行,这是错误的。我需要从块中排除该行,但如果任何记录具有 qcinfo <> 'Y',仍会为块生成随机记录。

select  t.chunk ,t.id, t.qcinfo, t.link from  table1
inner join
        (
        select chunk ,cast(min(id)+abs(random() % (max(id)-min(id)))as int) AS random_id
        from table1
        group by chunk
        ) sq
on      t.chunk = sq.chunk
and     t.id = sq.random_id
where qcinfo <> 'Y'
4

2 回答 2

3

有点hackish,但它的工作原理......见sql fiddle http://sqlfiddle.com/#!2/81e75/7

select  t.chunk
        ,t.link
from    table1 t
inner join
        (
        select chunk
               ,FLOOR(min(id) + RAND() * (max(id)-min(id))) AS random_id
        from    table1
        group by chunk
        ) sq
on      t.chunk = sq.chunk
and     t.id = sq.random_id

对不起,我以为你说的是​​ MySQL。这是小提琴和 SQLite 的代码

http://sqlfiddle.com/#!5/81e75/12

select  t.chunk
        ,t.link
from    table1 t
inner join
        (
        select chunk
               ,cast(min(id)+abs(random() % (max(id)-min(id)))as int) AS random_id
        from    table1
        group by chunk
        ) sq
on      t.chunk = sq.chunk
and     t.id = sq.random_id
于 2013-08-01T19:54:05.687 回答
0

请注意,当我们在没有聚合的情况下进行group by 时,SQLite 返回对应于组的第一个值

select link, chunk from table group by chunk;

运行你会得到这个

me1 | a
you2| d

现在您可以通过对表格进行随机排序然后分组来使第一个值随机化。这是最终的解决方案。

select link, chunk from (select * from table order by random()) group by chunk;
于 2020-10-11T12:26:19.900 回答