22,301
社区成员




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'主表')
AND type in (N'U')) --U 代表你查询的是表
DROP TABLE 主表
GO
---->建表
create table 主表([字段1] int)
insert 主表
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5
GO
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:子表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'子表')
AND type in (N'U')) --U 代表你查询的是表
DROP TABLE 子表
GO
---->建表
create table 子表([字段1] int,[字段2] varchar(1),[时间] datetime)
insert 子表
select 1,'a','20110101' union all
select 2,'b','20110102' union all
select 2,'c','20110103' union all
select 2,'d','20110104'
GO
select a.[字段1],[字段2]=(select top 1 [字段2] from 子表 where [字段1]=a.[字段1] order by [时间] desc),
[时间]=(select top 1 [时间] from 子表 where [字段1]=a.[字段1] order by [时间] desc)
from 主表 a
left join 子表 b on a.[字段1]=b.[字段1] group by a.[字段1]
/*
字段1 字段2 时间
----------- ---- -----------------------
1 a 2011-01-01 00:00:00.000
2 d 2011-01-04 00:00:00.000
3 NULL NULL
4 NULL NULL
5 NULL NULL
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:主表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'主表')
AND type in (N'U')) --U 代表你查询的是表
DROP TABLE 主表
GO
---->建表
create table 主表([字段1] int)
insert 主表
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5
GO
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:子表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'子表')
AND type in (N'U')) --U 代表你查询的是表
DROP TABLE 子表
GO
---->建表
create table 子表([字段1] int,[字段2] varchar(1),[时间] datetime)
insert 子表
select 1,'a','20110101' union all
select 2,'b','20110102' union all
select 2,'c','20110103' union all
select 2,'d','20110104'
GO
--> 查询结果
SELECT a.字段1,c.字段2,c.时间 FROM 主表 a
left join (select [字段1],max([时间] ) as [时间] from 子表 group by [字段1]) b
on a.字段1=b.字段1
left join 子表 c
on b.时间=c.时间
select *
from a left join (select * from b t where not exists (select 1 from b where 字段1 = t.字段1 and 时间 < t.时间))u
on a.字段1 = u.字段1