1

给定下表:

id | group_s | name
_____________________
1  |   1   | pollo
2  |   1   | cordero
3  |   1   | cerdo
4  |   2   | tomates
5  |   2   | naranjas
6  |   2   | manzanas

我想从每组中随机选择一行。可能的输出示例(因为它是随机的):

id | group_s | name
_____________________
3  |   1   | cerdo
5  |   2   | naranjas

或者

id | group_s | name
_____________________
1  |   1   | pollo
6  |   2   | manzanas

等等..

我不知道该怎么做。我想我应该多选表格。我确实尝试了以下但没有成功:

SELECT T2.* FROM (
SELECT group_s
FROM mytable
GROUP BY group_s ORDER BY RAND() LIMIT 1) AS T1
JOIN mytable AS T2
ON T1.group_s = T2.group_s;
4

1 回答 1

1

使用窗口函数ROW_NUMBER() OVER(PARTITION BY group_s)ORDER BY NEWID()随机获取排序,如下所示:

WITH CTE
AS
(
   SELECT *,
     ROW_NUMBER() OVER(PARTITION BY group_s 
                       ORDER BY newid()) AS RN
   FROM yourTable
)
SELECT id , group_s , name
FROM CTE
WHERE RN = 1;

在这里查看它的实际效果:

于 2013-07-04T15:00:46.543 回答