sql - Get random sample of customer IDs that meet multiple conditions
问题描述
I have a SQL table of customer data including the following columns:
ID, age, postcode, sign up method
I need to get a random sample of this data that meet a number of conditions:
- 20% one age group, 30% another age group
- 50 % female
- x% one region, y% another region, z% another region etc.
Does anyone know how I can do this? I have created random samples before but not with these kind of conditions
解决方案
我认为您需要 SQL 表中的 n 个随机行。
- 一个年龄组的 n1 行
- 来自另一个年龄组的 n2 行
- 一个区域的 n3 行
- ...
其中 n1 + n2 + n3 + ... = n。例如 PostgreSQL:
(SELECT * FROM customers
WHERE age > g0 AND age < g1
ORDER BY RANDOM()
LIMIT (n - n1))
UNION
(SELECT * FROM customers
WHERE age > g2 AND age < g3
ORDER BY RANDOM()
LIMIT (n - n2))
UNION
(SELECT * FROM customers
WHERE region = r0
ORDER BY RANDOM()
LIMIT (n - n3))
#g0,g1,g2,g3是年龄参数,r0是区域参数
推荐阅读
- image - 来自 Flutter Widget 的高分辨率图像
- php - 将动态徽标添加到 Genesis 主导航
- r - 使用 R 计算出现在同一组中的行数
- discord - 我如何知道我的 Windows 10 连接了多少台服务器?
- regex - 仅在 perl 正则表达式中匹配最后一次出现
- sql - 如何在特定事务的屏幕中从 SQLite 数据库中获取保存的数据?
- python - Python Socket 编码和解码客户端数据
- redis - 使用范围命令时是否可以使redis返回长值
- python - 3D 中的向量 3 体问题,向量需要 x、y、dy 和 dx 的错误
- html - 让 Boostrap 父 col 在子 col 之前崩溃?