求一条SELECT语句,有趣,常用,望高手解答
有一张表
t_test
id int4, 主健
user_id int4,
visit_date timestamp
要求输出id, user_id,visit_date ,但是user_id相同的记录并且visit_date里同一天的数据只输出当天时间最晚的一条,
而且, 排序是按 user_id 升序, visit_date 降序
insert into t_test values(1, 13, timestamp '2007-4-12 09:30:21 ');
insert into t_test values(2, 13, timestamp '2007-4-12 12:31:32 ');
insert into t_test values(3, 13, timestamp '2007-4-12 23:11:00 ');
insert into t_test values(4, 13, timestamp '2007-5-23 07:41:42 ');
insert into t_test values(5, 15, timestamp '2007-4-12 23:51:52 ');
正确输出应该是
id user_id visit_date
4 13 2007-05-23 07:41:42
3 13 2007-04-12 23:11:00
5 15 2007-04-12 23:51:52
谢谢
------解决方案--------------------select
t.*
from
t_test t
where
t.visit_date=(select max(visit_date) from t_test where user_id=t.user_id and datediff(day,visit_date,t.visit_date)=0)
------解决方案-------------------- create table #t(id int,[user_id] int,visit_date datetime)
insert into #t values(1, 13, '2007-4-12 09:30:21 ');
insert into #t values(2, 13, '2007-4-12 12:31:32 ');
insert into #t values(3, 13, '2007-4-12 23:11:00 ');
insert into #t values(4, 13, '2007-5-23 07:41:42 ');
insert into #t values(5, 15, '2007-4-12 23:51:52 ');
select *
from #t AS a
where id =
(
select top 1 id
from #t
where datediff(d,visit_date,a.visit_date)=0
and [user_id]=a.user_id
order by visit_date desc)
order by [user_id] ,visit_date desc
drop table #t