两表联结求一sql语句,和lambda表达式
两表联合求一sql语句,和lambda表达式
table1 主表
tid1 name
1 张一
2 张二
3 张三
4 张四
5 张五
table2 从表
tid2 tid1 time
1 1 2013-01-12
2 1 2013-03-12
3 1 2013-02-15
4 3 2013-05-12
5 2 2014-03-10
6 2 2014-10-10
想得到的数应为:(取时间最大的一条数据,没有时间的为空)
tid1 name time
1 张一 2013-03-12
2 张二 2014-10-10
3 张三 2013-05-12
4 张四 null
5 张五 null
怎么写sql语句啊,用lambda表达式如何写呢?
------解决方案--------------------
------解决方案--------------------
table1 主表
tid1 name
1 张一
2 张二
3 张三
4 张四
5 张五
table2 从表
tid2 tid1 time
1 1 2013-01-12
2 1 2013-03-12
3 1 2013-02-15
4 3 2013-05-12
5 2 2014-03-10
6 2 2014-10-10
想得到的数应为:(取时间最大的一条数据,没有时间的为空)
tid1 name time
1 张一 2013-03-12
2 张二 2014-10-10
3 张三 2013-05-12
4 张四 null
5 张五 null
怎么写sql语句啊,用lambda表达式如何写呢?
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-28 16:46:56
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([tid1] int,[name] varchar(4))
insert [table1]
select 1,'张一' union all
select 2,'张二' union all
select 3,'张三' union all
select 4,'张四' union all
select 5,'张五'
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
go
create table [table2]([tid2] int,[tid1] int,[time] datetime)
insert [table2]
select 1,1,'2013-01-12' union all
select 2,1,'2013-03-12' union all
select 3,1,'2013-02-15' union all
select 4,3,'2013-05-12' union all
select 5,2,'2014-03-10' union all
select 6,2,'2014-10-10'
--------------开始查询--------------------------
SELECT
a.tid1,a.name,b.time
FROM
[table1] AS a
LEFT JOIN [table2] AS b ON a.tid1=b.tid1
WHERE
NOT EXISTS ( SELECT
1
FROM
table2
WHERE
tid1=b.tid1 AND [time]<b.[time] )
----------------结果----------------------------
/* tid1 name time
----------- ---- -----------------------
1 张一 2013-01-12 00:00:00.000
2 张二 2014-03-10 00:00:00.000
3 张三 2013-05-12 00:00:00.000
4 张四 NULL
5 张五 NULL
(5 行受影响)
*/
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-28 16:46:56
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([tid1] int,[name] varchar(4))