Select 同一ID中随机几行table (T-SQL)

Select randomly few Rows of the same ID in the same table (T-SQL)

我正在尝试 select 随机 存储在一个 table 中的每个 ID 的几行,其中这些 ID 在这个 table.很难用语言来解释,所以让我用一个例子来告诉你:

来自 table 的示例:

Id  Review
1   Text11
1   Text12
1   Text13
2   Text21
3   Text31
3   Text32
4   Text41
5   Text51
6   Text61
6   Text62
6   Text63

预期结果:

Id  Review
1   Text11
1   Text13
2   Text21
3   Text32
4   Text41
5   Text51
6   Text62

事实上,table 包含数千行。一些 Id 仅包含一条评论,但其他 Id 可以包含数百条评论。我想 select 其中的 10%,并且 select 至少一次,所有有 1-9 条评论的行(我看到 SELECT TOP 10 percent FROM table ORDER BY NEWID() 包括该行,即使它是单独的) 我阅读了一些 Stack 主题,我想我必须使用子查询,但我没有找到正确的解决方案。

提前致谢。

此致。

试试这个:

DECLARE @t table(Id int, Review char(6))
INSERT @t values
(1,'Text11'),
(1,'Text12'),
(1,'Text13'),
(2,'Text21'),
(3,'Text31'),
(3,'Text32'),
(4,'Text41'),
(5,'Text51'),
(6,'Text61'),
(6,'Text62'),
(6,'Text63')

;WITH CTE AS
(
SELECT
  id, Review,
  row_number() over (partition by id order by newid()) rn, 
  count(*) over (partition by id) cnt
   FROM @t
 )
 SELECT id, Review
 FROM CTE
 WHERE rn <= (cnt / 10) + 1

结果(随机):

id  Review
1   Text12
2   Text21
3   Text31
4   Text41
5   Text51
6   Text63