我有下表:
Name Field
A 1
B 1
C 1
D 1
E 1
F 1
G 1
H 2
I 2
J 2
K 3
L 3
M 3
N 3
O 3
P 3
Q 3
R 3
S 3
T 3
我需要一个SQL查询,它会为列Field上的每个不同值生成一个包含5个随机行的集合。
例如,预期的结果:
Name Field
A 1
B 1
D 1
E 1
G 1
J 2
I 2
H 2
M 3
Q 3
T 3
S 3
P 3
有一种简单的方法吗?或者我应该将该表拆分为更多的表并为每个表生成随机数然后将它们联合起来吗?
答案 0 :(得分:5)
您可以CTE
使用ROW_NUMBER()
同时PARTITION
Field
使用;With Cte As
(
Select Name, Field,
Row_Number() Over (Partition By Field Order By NewId()) RN
From YourTable
)
Select Name, Field
From Cte
Where RN <= 5
来执行此操作:
{{1}}
答案 1 :(得分:3)
您可以使用select customer_id
from rental r
, inventory i
where r.inventory_id = i.inventory_id
group
by customer_id
having count(distinct i.store_id) = 2;
:
row_number()
答案 2 :(得分:0)
Gordon Linoff's code
的增强功能,如果您的查询中需要条件,此代码确实对我有帮助。
select *
from (select t.*,
row_number() over (partition by region order by newid()) as seqnum
from MyTable t
WHERE t.program = 'ACME'
) t
where seqnum <= 1500;