我有一张原始表:
我想编写一个查询,为每个[案例所有者]返回5个随机[案例编号]值。如果[案例所有者]少于5个案例,如Casper或Mark,则查询应返回这些代理的所有案例。所需的输出示例如下:
答案 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