/*
序號 名稱 分類 出現率
----------- ---- ----------- ---------------------------------------
1 aa 1 0.5
2 bb 1 0.5
3 cc 2 0.3
4 dd 2 0.6
5 ff 2 0.1
*/
--要求說明:
--例如上表中數據按照分類,分爲兩組1和2。
--分別得到每個分類的一條數據,讓數據出現的概率和字段中的出現率相符。
declare @T table
(序號 int,名稱 varchar(2),分類 int,出現率 numeric(2,1))
insert into @T
select 1,'aa',1,0.5 union all
select 2,'bb',1,0.5 union all
select 3,'cc',2,0.3 union all
select 4,'dd',2,0.6 union all
select 5,'ff',2,0.1
;with maco as
(
select a.* from @T a
right join master..spt_values b on 1=1
where type='p'and a.出現率*10>b.number
)
select
分類,(select top 1 名稱 from maco where 分類=t.分類
order by newid()) as 名稱
from maco t group by 分類
/*
分類 名稱
----------- ----
1 bb
2 dd
*/
示例來源:
http://social.microsoft.com/Forums/zh-CN/sqlserverzhchs/thread/33f20f9a-9750-409f-a1cc-99111dcbb5ff