首页 > 解决方案 > 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:

Does anyone know how I can do this? I have created random samples before but not with these kind of conditions

标签: sqlrandomsample

解决方案


我认为您需要 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是区域参数


推荐阅读