在Sqlite中随机播放数据

时间:2019-08-09 19:38:19

标签: sql sqlite notepad++ sqlite-net

我有类似

的数据
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 ++中可能吗?

2 个答案:

答案 0 :(得分:1)

如果您使用的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 id替换order by random()
请参见demo
如果您无法使用窗口功能:

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

请参见demo
结果:

| 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      |

答案 1 :(得分:1)

您可以在FOOD_TYPE ATTRIBUTE VALUE CNT SEQNUM Fruit Apple Sweet 1772 1 Fruit Apple Sour 1021 2 Fruit Apple Sweetest 930 3 Fruit Orange Sweetest 200 1 Fruit Orange Sour 190 2 Fruit Orange Sweetest 160 3 子句中使用row_number()进行此操作:

order by

通常“随机播放”暗含随机性(“交错”则不会)。如果那是您的意思:

select t.*
from t
order by row_number() over (partition by col3 order by col1),
         col1;