表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 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一条,谢谢
解决方案 »
- socket在IE中不能连接服务端????
- missing SQl property什么问题啊
- 高手指教--socket服务器提示:“Read Err64 提定的网络名不可用”的原因?
- [组件求助]Borland提供的标准组件可以修改吗?
- 关于三层连接的速度问题
- 还是activeform。下载了,但不运行,怎么回事?
- 怎样让win2000用程序关机,并且最后不出现“你可以安全的关闭计算机了”谢谢回复!
- 如何将多媒体文件保存到Oracle数据库中?
- 三层结构 存储blob失败? 告急 —— 大侠们帮忙,在线等
- 怎么让一个TEdit控件不能输入,但是里面的字是黑的,不是灰的??
- Delphi的Dll怎么产生Release版本?
- 关于VCL接口引用计数的问题, 高手请进
相对每一个ID的最后一条记录相加。
这一段什么意思,看不太明白。
B表
ID Name
1 名称1
2 名称2
3 名称3
A表中的ID,也就是B表中的ID
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
我用的是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
这句才是代码
把这句代码运行一下看看有没有你想要的答案
where bh in (select max(bh) from @a b where id=a.id)
会引起表扫描,数据量大的时候,会很慢
where a.bh=b.bh
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)