日期:2014-05-16  浏览次数:20372 次

【应用实例】之按照出现率显示数据--【叶子】
--数据
/*
序号          名称   分类          出现率
----------- ---- ----------- ---------------------------------------
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