现手里有张表,这张表中包含了一年帐期的手机的通话次数数据,想取最近5月,6月,7月个帐期通话次数为0的数据,写都通话次数为0的该怎么写呢
表A
号码 ID
123 2
236 3
258 4
369 5
741 6
789 7
145 8
表b
ID 帐期 通话次数
2 1201 10
2 1202 10
2 1203 10
2 1204 10
2 1205 0
2 1206 0
2 1207 0
4 1207 0
4 1206 0
4 1205 0
3 1204 10
3 1205 0
3 1206 0
3 1207 0select a.* , (select sum(通话次数)from b where a.ID=ID and 通话次数=0 and 帐期 in ('1205','1206','1207')) 次数为0  
from a a我这样写了,有人告诉我是错的,讲通话次数=0不起作用,还有该提数据在判断,我就有点蒙了,请高手指点哈,怎么才能先提数据在判断难得是这样写
select a.*,b.*
from a a,b,b
where a.ID=b.id
and  帐期  in ('1205','1206','1207')
要是这样写的话出来很多条重复的数据
出来就是
号码 ID 帐期 通话次数
123 2 1205 0
123 2 1206 0
123 2 1207 0
258 4 1205 0
258 4 1206 0
258 4 1207 0
236 3 1205 0
236 3 1206 0
我想要的结果是
号码 ID   最近3个月通话次数为0
123   2         0
258   4         0
236   3         0

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(小F,向高手学习)
    -- Date    :2012-07-17 15:17:06
    -- Version:
    --      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) 
    -- Apr 22 2011 11:57:00 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
    --
    ----------------------------------------------------------------
    --> 测试数据:[A]
    if object_id('[A]') is not null drop table [A]
    go 
    create table [A]([号码] int,[ID] int)
    insert [A]
    select 123,2 union all
    select 236,3 union all
    select 258,4 union all
    select 369,5 union all
    select 741,6 union all
    select 789,7 union all
    select 145,8
    --> 测试数据:[b]
    if object_id('[b]') is not null drop table [b]
    go 
    create table [b]([ID] int,[帐期] int,[通话次数] int)
    insert [b]
    select 2,1201,10 union all
    select 2,1202,10 union all
    select 2,1203,10 union all
    select 2,1204,10 union all
    select 2,1205,0 union all
    select 2,1206,0 union all
    select 2,1207,0 union all
    select 4,1207,0 union all
    select 4,1206,0 union all
    select 4,1205,0 union all
    select 3,1204,10 union all
    select 3,1205,0 union all
    select 3,1206,0 union all
    select 3,1207,0
    --------------开始查询--------------------------
    select
      distinct a.号码,a.id,b.通话次数
    from
      a join b
    on
      a.id=b.id
    where
      b.通话次数=0
    and
      帐期 in ('1205','1206','1207')
    ----------------结果----------------------------
    /* 号码          id          通话次数
    ----------- ----------- -----------
    123         2           0
    236         3           0
    258         4           0(3 行受影响)*/
      

  2.   

    高手,不好意思,我问了这边讲还是不对,提出问题了
    讲要这样的话是提的是4.5.6其中一个月通话次数为0的数据,
    讲有两种写法,不是很明白其中一句话请指导啊
    一种方法,4,5,6三月加起来,如果为0,即为0
    二种方法,4,5,6三个月分开写。
    对第一种,加起来,的那句如果为0,即为0
    不是很明白,
    对第二种大概是这样写的
    select *
    from temp_andy_hm a
    ,(select * from rpt_Yb_cdma_tc where 4) b
    ,(select * from rpt_Yb_cdma_tc where 5) c
    ,(select * from rpt_Yb_cdma_tc where 6) d
    请高手指教