【求助】SQL复杂查询,百思不得其解
建表SQL:
CREATE TABLE [dbo].[t_user](
[id] [nchar](10) NOT NULL,
[name] [nchar](10) NOT NULL,
[money] [int] NOT NULL,
[time] [datetime] NOT NULL,
CONSTRAINT [PK_t_user] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[t_user] ADD CONSTRAINT [DF_t_user_time] DEFAULT (getdate()) FOR [time]
GO
id name moneytime
1 zhangsan 1002013-03-04 16:45:55.760
2 lisi 1102013-03-04 16:46:09.917
3 wangwu 1202013-04-04 16:56:42.343
4 zhangsan 802013-05-04 16:56:54.123
5 zhangsan 2632013-06-04 16:57:02.230
6 lisi 642013-06-04 16:57:11.950
7 wangwu 2652013-07-04 16:57:21.850
8 lisi 2642013-07-04 16:57:32.730
id name moneytime
5 zhangsan 2632013-06-04 16:57:02.230
7 wangwu 2652013-07-04 16:57:21.850
8 lisi 2642013-07-04 16:57:32.730
[解决办法]
;with tmp
as(select *,rn=row_number()over(partition by name order by time desc) from t_user)
select * from tmp
where rn=1
[解决办法]
select * from t_user t
where id=(select top 1 id from t_user where name=t.name order by [time] desc)
select * from [t_user]
where time in (select max(time) from [t_user]
group by name )
这个可以,不过如果时间相同,比如如下数据:
id name moneytime
1 zhangsan 1002013-03-04 16:45:55.760
2 lisi 1102013-03-04 16:46:09.917
3 wangwu 1202013-04-04 16:56:42.343
4 zhangsan 802013-05-04 16:56:54.123
5 zhangsan 2632013-06-04 16:57:02.230
6 lisi 642013-06-04 16:57:11.950
7 wangwu 2652013-07-04 16:57:21.850
8 lisi 2642013-07-04 16:57:32.730
9 lisi 2412013-07-04 16:57:32.730
使用
select * from [t_user]
where time in (select max(time) from [t_user]
group by name )
得到的结果如下:
id name moneytime
5 zhangsan 2632013-06-04 16:57:02.230
7 wangwu 2652013-07-04 16:57:21.850
8 lisi 2642013-07-04 16:57:32.730
9 lisi 2412013-07-04 16:57:32.730
不过,谢谢回复!
select * from [t_user]
where id in(
select MAX(id) from [t_user]
where time in (select max(time) from [t_user]
group by name
)
group by name)