我想为他们的playerRole专栏获得3个不同的玩家。我正在使用
SELECT TOP 1 * FROM FantasyPlayers WHERE playerRole = 1 ORDER BY NEWID()
查询获取playerRole = 1的随机行
但是我想得到
SELECT TOP 1 * FROM FantasyPlayers WHERE playerRole = 1 ORDER BY NEWID()
SELECT TOP 1 * FROM FantasyPlayers WHERE playerRole = 2 ORDER BY NEWID()
SELECT TOP 1 * FROM FantasyPlayers WHERE playerRole = 3 ORDER BY NEWID()
3个具有3个不同角色的随机玩家,这意味着每个玩家角色有1个随机玩家。
我尝试了由于NEWID()
而没有返回任何内容的Union感谢任何帮助
由于
答案 0 :(得分:2)
...也许
WITH CTE AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY playerRole
ORDER BY NEWID()) AS RN
FROM FantasyPlayers)
SELECT *
FROM CTE
WHERE RN = 1;
答案 1 :(得分:2)
您也可以在没有子查询的情况下执行此操作:
select top (1) with ties fp.*
from FantasyPlayers fp
order by row_number() over (partition by playerRole order by newid();