ID FK 第几次 其他字段        总次数
2933 322722 第2次     1 3 1          2
2923 322722 第1次     1 1 原址查无此人 2
2922 371911 第1次     1 7 原写地址不详 1
数据库的数据:去掉最后一列总次数显示的数据:加上总次数一列,并且可以作为查询条件 这个sql 该怎么写,求教

解决方案 »

  1.   

    select *,(select count(*) from tab where id = a.id 
    and fk = a.fk --也许不必这个条件,自己判断
    ) as 总次数
    from tab a
      

  2.   


    用公用表表达式可以实现..假设表名为TB
    ;with
    dd as(
    select id,sum(id) as nb --总次数
    from tb 
    group by id
    )
    select tb.*
    from tb,dd
    where dd.nb>2 --查询总次数大于2的记录
          and dd.id=tb.id
      

  3.   


    declare @t table (ID int,FK int,第几次 varchar(5),其他字段 varchar(12))
    insert into @t
    select 2933,322722,'第2次','1' union all
    select 2923,322722,'第1次','原址查无此人' union all
    select 2922,371911,'第1次','原写地址不详'select *,总次数=(select count(*) from @t where FK=a.FK) from @t a
    /*
    ID          FK          第几次   其他字段         总次数
    ----------- ----------- ----- ------------ -----------
    2933        322722      第2次   1            2
    2923        322722      第1次   原址查无此人       2
    2922        371911      第1次   原写地址不详       1
    */
      

  4.   

    select
       a.*,b.num as   总次数
    from
       tb a,
       (select id,sum(id) as num from tb group by id)b
    where
       a.id=b.id