表中记录了手机欠费的情况,有三个字段
mobile_no(手机号码),date(欠费年月),money(当月欠费金额)
如:
13302710113        200307           122
现在要统计连续三个月都欠费的手机号码,以及欠费总金额
能直接利用Sql语句得到上面的结果吗?

解决方案 »

  1.   

    一定要用SQL吗?不能选出来再判断或者过滤一下?以下不知道你的数据库是否支持
    select mobile_no
    from t
    where count(*)>=3
    group by mobile_no
    ;select mobile_no
    from t
    where date='200307' and mobile_no in (select mobile_no
          from t
          where date='200306' and mobile_no in select mobile_no
                from t
                where date='200305' and mobile_no in))
    ;
      

  2.   

    少了个括号,日期你可以用变量生成select mobile_no
    from t
    where date='200307' and mobile_no in (select mobile_no
          from t
          where date='200306' and mobile_no in (select mobile_no
                from t
                where date='200305' and mobile_no in))
    ;
      

  3.   

    后面还有点多余的,这下应该正确了select mobile_no
    from t
    where date='200307' and mobile_no in (select mobile_no
          from t
          where date='200306' and mobile_no in (select mobile_no
                from t
                where date='200305'))
    ;
      

  4.   

    试试这个:
    select
          a.mobile_no as 手机号码,(a.money+b.money+c.money) as 欠费总额
    from 
        table as a,table as b,table as c
    where
         a.mobile_no=b.mobile_no and a.mobile_no=c.mobile_no
         and a.date='200307',b.date='200306',c.date='200305'
      

  5.   

    应该是:
    select
          a.mobile_no as 手机号码,(a.money+b.money+c.money) as 欠费总额
    from 
        table as a,table as b,table as c
    where
         a.mobile_no=b.mobile_no and a.mobile_no=c.mobile_no
         and a.date='200307' and b.date='200306' and c.date='200305'
      

  6.   

    我说的连续三个月不见的是200307,200306,200305,而是表中记录里所有的任何连续的三个月。我想,直接用sql语句实现也许不太可能,就算用程序实现,好像也有些麻烦呢,首先就涉及到怎么样判断给定的几个月是否有连续的三个月,包括跨年份的
      

  7.   

    我看单独用SQL语句无法实现
    提点建议:
    把数据库按主关键字:手几号码,次关键字:前费年月升序排序
    用存储过程或编写Delphi程序从数据开头逐条判断
    用三个变量,一个记录手机号码num,一个记录欠费年月date,欠费的月数n
    按如下步骤完成:
    while not 表单.eof do
    begin
    if num=手机号码 then 
      if n<3
      begin
         if date-欠费年月=1个月 then
         begin
            n=n+1
            if n=3 then 
               记录该手机号//再用一个临时表单
         end
      end 
      else
      begin
         n=1
         num=手机号
         date=欠费年月
      end  
      到下一条纪录
    end
      

  8.   

    嗯,现在我也觉得无法用sql语句就解决问题,
    我已经编写了一段程序,完成了上述功能
    非常感谢大家对我的热情帮助!