随机选择数据

wang7890 2008-10-28 10:35:51
表A 有如下数据:

ID IDNAME TYPE
1 q 1
2 w 1
3 e 1
4 r 1
5 t 1
6 y 2
7 u 2
8 i 2
9 o 2
10 p 2
11 a 3
12 s 3
13 d 3
14 f 3
15 g 3
16 h 3

从中随机选择3个TYPE 为1 ,2个TYPE为2,3个TYPE为3 的数据,
结果类似如下所示:
2 w 1
3 e 1
4 r 1
9 o 2
7 u 2
13 d 3
14 f 3
15 g 3

请大家赐教,如何在一条SQL 语句中实现,我循环了3次分别取出来, 这样很是浪费时间!!
...全文
51 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangzeDB 2008-10-28
  • 打赏
  • 举报
回复

--> --> (jake)生成测试数据

declare n number;
begin
select count(*) into n from user_tables where table_name=upper('T_20081028');
if n>0 then
execute immediate 'drop table T_20081028';
end if;
end;
Create table T_20081028
as
select 1 id ,'q' idname,1 type from dual union all
select 2,'w',1 from dual union all
select 3,'e',1 from dual union all
select 4,'r',1 from dual union all
select 5,'t',1 from dual union all
select 6,'y',2 from dual union all
select 7,'u',2 from dual union all
select 8,'i',2 from dual union all
select 9,'o',2 from dual union all
select 10,'p',2 from dual union all
select 11,'a',3 from dual union all
select 12,'s',3 from dual union all
select 13,'d',3 from dual union all
select 14,'f',3 from dual union all
select 15,'g',3 from dual union all
select 16,'h',3 from dual
;
Select * from T_20081028



select * from
(
select * from T_20081028 where TYPE=1
order by dbms_random.value
)
where rownum <= 3
union all
select * from
(
select * from T_20081028 where TYPE=2
order by dbms_random.value
)
where rownum <= 2
union all
select * from
(
select * from T_20081028 where TYPE=3
order by dbms_random.value
)
where rownum <= 3;
hyrongg 2008-10-28
  • 打赏
  • 举报
回复

SQL> select * from t;

ID IDNAME TYPE
--- ------------ ----
1 q 1
2 w 1
3 e 1
4 r 1
5 t 1
6 y 2
7 u 2
8 i 2
9 o 2
10 p 2
11 a 3
12 s 3
13 d 3
14 f 3
15 g 3
16 h 3

16 rows selected

SQL>
SQL> select * from (
2 select * from t where type=1 order by dbms_random.value
3 ) where rownum<=3
4 union
5 select * from (
6 select * from t where type=2 order by dbms_random.value
7 ) where rownum<=2
8 union
9 select * from (
10 select * from t where type=3 order by dbms_random.value
11 ) where rownum<=3;

ID IDNAME TYPE
---------- ------------ ----------
1 q 1
2 w 1
5 t 1
6 y 2
8 i 2
13 d 3
14 f 3
16 h 3

8 rows selected

SQL>
SQL> select * from (
2 select * from t where type=1 order by dbms_random.value
3 ) where rownum<=3
4 union
5 select * from (
6 select * from t where type=2 order by dbms_random.value
7 ) where rownum<=2
8 union
9 select * from (
10 select * from t where type=3 order by dbms_random.value
11 ) where rownum<=3;

ID IDNAME TYPE
---------- ------------ ----------
3 e 1
4 r 1
5 t 1
7 u 2
10 p 2
11 a 3
14 f 3
15 g 3

8 rows selected

SQL>

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧