表ABH   ID    Count   
1    1      3
2    2      4
3    1      5
4    1      8
5    2      6
6    2      7
8    3      1
9    3      2BH,是记录顺序
ID,是编号
Count,是数量
得到汇总:BH为4的Count+BH为6的Count+BH为9的Count
相对每一个ID的最后一条记录相加。
求SQL一条,谢谢

解决方案 »

  1.   

    BH为4的Count+BH为6的Count+BH为9的Count
    相对每一个ID的最后一条记录相加。
    这一段什么意思,看不太明白。
      

  2.   

    还有一个表
    B表
       ID    Name
       1     名称1
       2     名称2
       3     名称3
    A表中的ID,也就是B表中的ID
      

  3.   

    看看可以不
    declare @a Table(BH int,ID int,[COUNT] int)
    Insert @a Select    1,    1,     3
    Union All Select   2,    2,     4
    Union All Select   3,    1,     5
    Union All Select   4,    1,     8
    Union All Select   5,    2,   6
    Union All Select   6,    2,   7
    Union All Select   8,    3,   1
    Union All Select   9,    3,   2select * from @aselect sum([count])as last_count from ( select * from @a b where not exists
    (select 1 from @a where [ID]=b.[ID] and BH>b.BH))b
      

  4.   

    我写出来了,楼上我看不懂你的代码,存储过程吧,我用的是ACCESS,不管怎么样,谢谢你。
      

  5.   

    在access可以运行吗
    我用的是SQL declare @a Table(BH int,ID int,[COUNT] int)
    Insert @a Select    1,    1,     3
    Union All Select   2,    2,     4
    Union All Select   3,    1,     5
    Union All Select   4,    1,     8
    Union All Select   5,    2,   6
    Union All Select   6,    2,   7
    Union All Select   8,    3,   1
    Union All Select   9,    3,   2select * from @a
    上面的是测试环境select sum([count])as last_count from ( select * from @a b where not exists
    (select 1 from @a where [ID]=b.[ID] and BH>b.BH))b
    这句才是代码
    把这句代码运行一下看看有没有你想要的答案
      

  6.   

    select sum(count) from @a  a
    where  bh in (select max(bh) from @a b where id=a.id)
      

  7.   

    nekiy的是可以的,但在表大的时候,由于not exists
    会引起表扫描,数据量大的时候,会很慢
      

  8.   

    select sum(count) from test1 a ,(select id,max(bh) as bh from test1   group by id) b
    where a.bh=b.bh
      

  9.   

    select sum(count) from table where BH=4 or BH=6 or BH=9
      

  10.   

    declare @a Table(BH int,ID int,[COUNT] int)
    Insert @a Select    1,    1,     3
    Union All Select   2,    2,     4
    Union All Select   3,    1,     5
    Union All Select   4,    1,     8
    Union All Select   5,    2,   6
    Union All Select   6,    2,   7
    Union All Select   8,    3,   1
    Union All Select   9,    3,   2
    --方法1.
    select sum(count) as count from @a A
    where not exists
    ( select 1 from @a where id=A.id and bh>A.bh)
    --方法2.
    select sum(count) as count from @a A
    where bh in (select top 1 bh from @a where id=A.id order by bh desc)
      

  11.   

    谢谢大家,搞定了,我用的是keiy() 的方法