Sql从同一个表中的子组中多次选择一行

时间:2013-07-04 14:55:32

标签: mysql sql multi-select

鉴于下表:

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;

1 个答案:

答案 0 :(得分: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;

请在此处查看: