一个查询的问题

tonysunny 2011-02-24 04:47:36
主表
字段1
1
2
3
4
5
----------------------
子表
字段1 字段2 时间
1 a 20110101
2 b 20110102
2 c 20110103
2 d 20110104
-----------------------

查询结果
字段1 字段2 时间
1 a 20110101
2 d 20110104
3 null null
4 null null
5 null null
-------------------------
请问怎么写呢?同时要考虑效率的情况下
...全文
52 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
快溜 2011-02-24
  • 打赏
  • 举报
回复
 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
王向飞 2011-02-24
  • 打赏
  • 举报
回复

--> 数据库版本:
--> 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.时间



AcHerat 2011-02-24
  • 打赏
  • 举报
回复

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

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧