sql - 在 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++ 中吗?
解决方案
如果您使用的 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()
.
请参阅演示。
如果您不能使用窗口函数:
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 |
推荐阅读
- flutter - 如何在颤动中实现这种形状?
- javascript - 获取 API- res.json() 返回一个 [object][object]
- php - MySQL查询从表2中获取总项目数到表1中的所有者?
- swift - 如何快速更改内容?
- momentjs - 将毫秒传递给 moment() 时如何获取实际的实时日期
- windows - 一个驱动程序可以包装另一个驱动程序以使用 WEBUSB
- android - 如何在android中创建s曲线布局
- java - 如何在 Java 中对用户定义的双向链表进行排序?
- c++ - 如何使用 SHA1 散列算法在 C++ 中散列系统时间?
- protractor - protractorBy 是做什么的?