我有以下表格:
id | customer | type
---+----------+------
1 | Joe | 5
2 | Sally | 3
3 | Joe | 2
4 | Sally | 1
5 | Bob | 5
6 | Clark | 5
7 | Daniel | 1
8 | Mike | 3
以及以下数据:
count | type
------+------
2 | 5
1 | 1
1 | 3
或只是数组:
(5, 5, 1, 3)
我需要在一个请求中选择2个类型为5的随机唯一客户,1个类型1的客户和1个类型3 的客户
答案 0 :(得分:3)
这就像juergen的方法,但它适用于任何类型的配置。
select t1.id
from
(
select c.id,
t.count,
row_number () over (partition by t.type order by newid()) as rn
from customerTable c join typeTable t on c.type = t.type) as t1
where t1.rn <= t1.count;