日期:2014-05-18 浏览次数:20567 次
--这样吗?
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2012-07-17 14:56:27
-- 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)
--
----------------------------
--> 测试数据:[Tb1]
if object_id('[Tb1]') is not null drop table [Tb1]
go
create table [Tb1]([code] varchar(3),[number] int,[datetime] datetime)
insert [Tb1]
select '001',2,'2012-3-2' union all
select '001',5,'2012-3-3' union all
select '002',3,'2012-3-4' union all
select '001',5,'2012-3-4'
--> 测试数据:[Tb2]
if object_id('[Tb2]') is not null drop table [Tb2]
go
create table [Tb2]([code] varchar(3),[datetime] datetime)
insert [Tb2]
select '001','2012-3-3' union all
select '002','2012-3-6' union all
select '001','2012-3-2'
--------------开始查询--------------------------
select
a.code,sum(a.number) as number
from
tb1 a join tb2 b
on
a.code=b.code
where
b.datetime=(select max(datetime) from tb2 where code=b.code)
and
a.datetime>b.datetime
group by
a.code
----------------结果----------------------------
/* code number
---- -----------
001 5
(1 行受影响)
*/