日期:2014-05-18  浏览次数:20465 次

统计数据出现的次数
比如说 10条记录

1
2
3
2
5
2
3
8
9


2后面连续出3的了两次 ,那么 2-3 结果为 2/10
2-5 为1/10

------解决方案--------------------
SQL code

declare @T table (id int)
insert into @T
select 1 union all
select 2 union all
select 3 union all
select 2 union all
select 5 union all
select 2 union all
select 3 union all
select 8 union all
select 9 union all
select 7

select  '2' + '-' + ltrim(number) as c1 ,
        ltrim(count(b.id)) + '/' + ltrim(( select   count(1)
                                           from     @t
                                         )) as c2
from    master..spt_values c
        left join ( select  row_number() over ( order by getdate() ) as rid ,
                            *
                    from    @t
                  ) a on a.id = 2
        left join ( select  row_number() over ( order by getdate() ) as rid ,
                            *
                    from    @t
                  ) b on a.rid = b.rid - 1
                         and b.id = c.number
where type = 'p' and number between 1 and 9 group by '2' + '-' + ltrim(number)

/*
c1             c2
-------------- -------------------------
2-1            0/10
2-2            0/10
2-3            2/10
2-4            0/10
2-5            1/10
2-6            0/10
2-7            0/10
2-8            0/10
2-9            0/10
*/

------解决方案--------------------
SQL code

declare @T table (id int)
insert into @T
select 1 union all
select 2 union all
select 3 union all
select 2 union all
select 5 union all
select 2 union all
select 3 union all
select 8 union all
select 9 union all
select 7

--刚才是为了写成一句,所以嵌套了多次

--SQL SERVER 2005
;WITH M AS (select row_number() over (order by getdate()) as rid,* from @t)

select '2-' + ltrim(number) as c1,ltrim(count(b.id)) + '/10' as c2
from master..spt_values c left join M a on a.id = 2 
                          left join M b on a.rid = b.rid - 1 and b.id = c.number
where type = 'p' and number between 1 and 9 group by ltrim(number)

/*
c1             c2
-------------- ---------------
2-1            0/10
2-2            0/10
2-3            2/10
2-4            0/10
2-5            1/10
2-6            0/10
2-7            0/10
2-8            0/10
2-9            0/10
*/

------解决方案--------------------
SQL:
select count(1) 数量 ,数字 from 记录表 
where 标识列 >= ( select 标识列 from 记录表 where 数字=2 order by 标识列)
 group by 数字


后台:
返回DataTable dt
int count=0;
for(int i=1; i<=10 i++)
{
for(int j=0 ; j<dt.Rows.Count;j++)
{
if(Convert.ToInt32(dt[j]["数字"])==i)
{
count=Convert.ToInt32(dt[j]["数量"]);
]
}
//2-i count/10
}