假设有table:CREATE TABLE Fact_Sale_Profit (
pid number(6),
storeid number(6),
cid number(8),
tdate date,
price number(6),
sale number(8),
profit number(8),
PRIMARY KEY (pid, storeid, cid, tdate, price)
);给定时间段2009-10-15到2009-11-15,请问如何获得时间段内“每周”采购次数(即出现在Fact_Sale_Profit表中次数)多于2次的cid?非常感谢!

解决方案 »

  1.   

    没看懂。  "每周采购次数多于2次的客户" 是指什么? 在所有周这个用户的采购次数都>2?
    建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试。   
      

  2.   

    select id from 
    (select to_char(tdate,'YYYY-IW'),id,count(id) c from Fact_Sale_Profit where tdate between to_date('2009-10-15','YYYY-MM-DD') and to_date('2009-11-15','YYYY-MM-DD')
    group by to_char(tdate,'YYYY-IW'),id
    ) where c>=2;
      

  3.   

    #2:
    上面给出的就是我的表结构。数据库用的是oracle 8.1。
    需要的结果是在给定的时间段内,每一周都有采购(即每周这个cid都出现在Fact_Sale_Profit表中,),并且cid出现的次数大于两次(即count(cid)>2)。
    特别注意的是这个cid要求“所有周”都有采购。若期间只有部分周的采购大于2次,不包含在内。#3
    的方法是:select cid from 
    (select to_char(tdate,'YYYY-IW'),cid,count(cid) c from Fact_Sale_Profit where tdate between to_date('2009-10-15','YYYY-MM-DD') and to_date('2009-11-15','YYYY-MM-DD') 
    group by to_char(tdate,'YYYY-IW'),cid 
    ) where c=1;这个方法无法cid在保证“所有周”都有两次以上的采购,而是列出了在有“部分周”2次以上采购的cid。而且输出结果会把同一个cid输出多次(如果该cid在多个周都>2次)如:
    TO_CHAR        CID          C
    -------        -----       ----
    2009-41        36          3
    2009-44        36          5
    2009-46        36          3请问谁还有更好的办法?
      

  4.   


    我以为你要的是只要某周超过的就行呐。
    要改的话,
    这里已经按id、周分组了。只要查出总周数,然后算 cid是否等于这个周数做个连接就好啦。
    不过要考虑跨年的情况。
      

  5.   

    我也在考虑算出给定时间段内的周数w1,在计算cid采购大于2次的周数w2,当w1=w2是则符合条件。
    select count(c) from 
    (select to_char(tdate,'YYYY-IW'),cid,count(cid) c from Fact_Sale_Profit where tdate between to_date('2009-10-15','YYYY-MM-DD') and to_date('2009-11-15','YYYY-MM-DD') 
    group by to_char(tdate,'YYYY-IW'),cid 
    ) where c>=2;
    以上代码可以获得w2
    但是如何获得给定时间段内的总周数(w1)?怎么将两个时间相减得到这两个时间点之间的周数?
      

  6.   


    SQL> select to_number(to_char(to_date('2009-11-15','YYYY-MM-DD'),'IW'),'99')-to_number(to_char(to_date('2009-10-15','YYYY-MM-DD'),'IW'))+1 from dual;TO_NUMBER(TO_CHAR(TO_DATE('2009-11-15','YYYY-MM-DD'),'IW'),'99')-TO_NUMBER(TO_CH
    --------------------------------------------------------------------------------
                                                                                   5跨年的我不会。