34,594
社区成员
发帖
与我相关
我的任务
分享
' 求一个SQL的SELECT语句,用于连接两个表
' 并且依照日期的大小,返回最新的不重复记录,具体期望如下:
' 1、在[Products]表中寻找所有Username等于[Users]表中的Username的记录
' 2、在上述基础上以[Products]表中的CompleteDate字段作为条件获取不重复的唯一记录
' 3、把[Products]得到的结果与表[Users]连接,得到结果集
' 因为[Products]的Username字段中并没出现“李四”的记录
' 因此结果集只需要返回两笔不重复的记录
' 请问这个SELECT语句该如何编写?谢谢!
' 表Users
' UID Username Department
'--------------------------------------------------------------
' 1 张三 生产部
' 2 李四 研发部
' 3 王五 品质部
' 表Products
'--------------------------------------------------------------
' ProID Username Item CompleteDate
' 1 张三 开料 2012-6-8
' 2 王五 抽检 2012-6-8
' 3 王五 出货检验 2012-6-10
' 4 张三 送检 2012-6-9
' 5 王五 打包装 2012-6-9
' 期望得到结果集
' UID Username Department ProID Item CompleteDate
'---------------------------------------------------------------
' 3 王五 品质部 3 出货检验 2012-6-10
' 1 张三 生产部 4 送检 2012-6-9
SELECT B.UID,B.Username,B.Department,A.ProID,A.Item,A.CompleteDate
FROM [Products] A,[Users] B
WHERE A.Username = B.Username
AND NOT EXISTS (
SELECT 1
FROM [Products] C
WHERE A.Username = C.Username
AND C.CompleteDate > A.CompleteDate
)
;with t
as(
select
u.uid,
u.Username,
u.Department,
p.ProID,
p.Item,
p.CompleteDate
from Users u
inner join Products p
on u.Username=p.Username
)
select
*
from
t
where
t.CompleteDate=(select max(a.CompleteDate) from t a where a.username=t.uaername)
---------------------创建表以及插入数据,开始-----------------------------------
if(object_id('a')is not null) drop table a
go
create table a
(
UID int,
Username varchar(50),
Department varchar(50)
)
go
insert into a
select 1,'张三','生产部' union all
select 2,'李四','研发部' union all
select 3,'王五','品质部'
go
if(object_id('b')is not null) drop table b
go
create table b
(
ProID int,
Username varchar(50),
Item varchar(50),
CompleteDate datetime
)
go
insert into b
select 1,'张三','开料','2012-6-8' union all
select 2,'王五','抽检','2012-6-8' union all
select 3,'王五','出货检验','2012-6-10' union all
select 4,'张三','送检','2012-6-9' union all
select 5,'王五','打包装','2012-6-9'
go
---------------------创建表以及插入数据,结束-----------------------------------
--开始select
select a.UID,a.username,a.Department,b.ProID,b.Item,
convert(char(10),b.CompleteDate,121)as CompleteDate
from a inner join b on a.username = b.username
inner join (select username,max(completeDate)as CompleteDate from b group by username)as c on b.username = c.username and c.CompleteDate = b.CompleteDate
--结果展示
/*
UID username Department ProID Item CompleteDate
----------- -------------------------------------------------- -------------------------------------------------- ----------- -------------------------------------------------- ------------
1 张三 生产部 4 送检 2012-06-09
3 王五 品质部 3 出货检验 2012-06-10
(2 行受影响)
*/