34,576
社区成员
发帖
与我相关
我的任务
分享
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[用户名] varchar(2),[文件时间] datetime,[文件大小] varchar(5))
insert [tb]
select 1,'aa','2010-1-17 10:40','0.1MB' union all
select 2,'cc','2010-1-18 12:40','0.3MB' union all
select 3,'aa','2010-1-18 10:40','0.7MB' union all
select 4,'aa','2010-1-17 20:40','0.1MB' union all
select 5,'cc','2010-1-17 10:40','0.1MB' union all
select 6,'bb','2010-1-17 10:40','0.1MB'
select * from tb t where not exists (select * from tb where 文件时间>t.文件时间 and 用户名=t.用户名)
-or
select * from [tb] t
where not exists (select 1 from [tb] where [用户名]=t.[用户名] and [文件时间] > t.[文件时间])
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb]([id] int,[用户名] varchar(2),[文件时间] datetime,[文件大小] varchar(5))
insert [tb]
select 1,'aa','2010-1-17 10:40','0.1MB' union all
select 2,'cc','2010-1-18 12:40','0.3MB' union all
select 3,'aa','2010-1-18 10:40','0.7MB' union all
select 4,'aa','2010-1-17 20:40','0.1MB' union all
select 5,'cc','2010-1-17 10:40','0.1MB' union all
select 6,'bb','2010-1-17 10:40','0.1MB'
select * from [tb] t
where [文件时间]=(select max([文件时间]) from [tb] where [用户名]=t.[用户名])
------------------------
2 cc 2010-01-18 12:40:00.000 0.3MB
6 bb 2010-01-17 10:40:00.000 0.1MB
3 aa 2010-01-18 10:40:00.000 0.7MB
----------------------------------------------------------------
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2010-01-19 11:54:25
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[用户名] varchar(2),[文件时间] datetime,[文件大小] varchar(5))
insert [tb]
select 1,'aa','2010-1-17 10:40','0.1MB' union all
select 2,'cc','2010-1-18 12:40','0.3MB' union all
select 3,'aa','2010-1-18 10:40','0.7MB' union all
select 4,'aa','2010-1-17 20:40','0.1MB' union all
select 5,'cc','2010-1-17 10:40','0.1MB' union all
select 6,'bb','2010-1-17 10:40','0.1MB'
--------------开始查询--------------------------
select
*
from
tb t
where
文件时间=(select max(文件时间) from tb where 用户名=t.用户名)
----------------结果----------------------------
/* id 用户名 文件时间 文件大小
----------- ---- ----------------------- -----
2 cc 2010-01-18 12:40:00.000 0.3MB
6 bb 2010-01-17 10:40:00.000 0.1MB
3 aa 2010-01-18 10:40:00.000 0.7MB
(3 行受影响)
*/
select
*
from
tb t
where
文件时间=(select max(文件时间) from tb where 用户名=t.用户名)