2016-08-18 87 views
1

我具有以下表中的每个类型的随机行:SQL服务器:选择

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个客户和类型3的1个客户在一个请求中

回答

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; 
+1

谢谢!正是我需要的 –