表结构为,其中部分数据如下
日期 关键字
.
.
.
2010-12-01 A
2010-12-01 B
2010-12-01 C
2010-12-02 C
2010-12-03 A
2010-12-04 B
2010-12-05 D
2010-12-06 A
.
.
.
求SQL语句。
要求搜索2010-12-01 至 2010-12-06 之间各关键字出现的次数及几率。正确结果应该为
A 3次 几率为1/3 + 1 + 1
B 2次 1/3 + 1
C 2次 1/3 + 1
D 1次 1说明:比如2010-12-01有3个关键字,A,B,C均分即1/3

解决方案 »

  1.   

    --> 测试数据:#1
    if object_id('tempdb.dbo.#1') is not null drop table #1
    create table #1([rq] datetime,[ky] varchar(1))
    insert #1
    select '2010-12-01','A' union all
    select '2010-12-01','B' union all
    select '2010-12-01','C' union all
    select '2010-12-02','C' union all
    select '2010-12-03','A' union all
    select '2010-12-04','B' union all
    select '2010-12-05','D' union all
    select '2010-12-06','A'
    select ky,count(ct),sum(ct*1.0/su)
    from (
    select ky,COUNT(1) as ct,su=(select COUNT(1) from #1 where rq=t.rq) from #1 t 
    group by ky  ,rq) mm
    group by ky
      

  2.   

    非常感谢楼上的。完了才发现因为我是Sqlite中使用,不支持嵌套,所以总提示SQL Error: no such column: su  <select ky,count(ct),sum(ct*1.0/su)
    from (
    select ky,COUNT(1) as ct,su=(select COUNT(1) from test where rq=t.rq) from test t
    group by ky  ,rq) mm
    group by ky>
      

  3.   

    select ky,count(ct),sum(ct*1.0/su)
    from (
    select ky,COUNT(1) as ct,su=(select COUNT(1) from #1 where rq=t.rq) from #1 t 
    group by ky ,rq) mm
    group by ky这个写法不错