每个Distinct值选择5个随机行

时间:2018-03-09 11:57:24

标签: sql-server random distinct

我有一张原始表:

Raw Table enter image description here

我想编写一个查询,为每个[案例所有者]返回5个随机[案例编号]值。如果[案例所有者]少于5个案例,如Casper或Mark,则查询应返回这些代理的所有案例。所需的输出示例如下:

Desired Output enter image description here

2 个答案:

答案 0 :(得分:0)

如果要随机选择,请根据随机数的顺序和case owner分组给出行号,然后选择行号从1到5的行。

<强>查询

;with cte as(
    select [rn] = row_number() over(
        partition by [case owner]
        order by ABS(CHECKSUM(NewId())) % 100
    ), *
    from [your_table_name]
)
select [case owner], [case number] 
from cte
where [rn] < 6;

答案 1 :(得分:0)

以下查询将为您提供所需的输出。

 SELECT [Case Owner],[Case Number] FROM
 (
  SELECT [Case Owner],[Case Number], 
   ROW_NUMBER() OVER (PARTITION BY [Case Owner] ORDER BY NEWID()) RN
  FROM [Your_Table]
 )T
 WHERE T.RN < 6