首页 > 解决方案 > 在 Sqlite 中随机播放数据

问题描述

我有一个像

id1,apple,0
id2,orange,0
id3,banana,0
id4,carrot,0
ida,kiwi,1
idb,potato,1
idc,cakes,1
idd,chocos,1

我需要在最后一列(0 THEN 1)的基础上洗牌,比如

id1,apple,0
ida,kiwi,1
id2,orange,0
idb,potato,1
id3,banana,0
idc,cakes,1
id4,carrot,0
idd,chocos,1

这可能在 sqlite 或 notepad++ 中吗?

标签: sqlsqlitenotepad++sqlite-net

解决方案


如果您使用的 SQLite 版本支持它,您可以使用row_number()窗口函数:

select t.id, t.fruit, t.number 
from (
  select *, 
    row_number() over (partition by number order by id) rn 
  from tablename
) t
order by t.rn

如果您需要随机排列的行,请替换order by idorder by random().
请参阅演示
如果您不能使用窗口函数:

select t.id, t.fruit, t.number 
from (
  select t.*,
    (select count(*) from tablename where number = t.number and id < t.id) rn
  from tablename t
) t
order by t.rn

请参阅演示
结果:

| id  | fruit  | number |
| --- | ------ | ------ |
| id1 | apple  | 0      |
| ida | kiwi   | 1      |
| id2 | orange | 0      |
| idb | potato | 1      |
| id3 | banana | 0      |
| idc | cakes  | 1      |
| id4 | carrot | 0      |
| idd | chocos | 1      |

推荐阅读