日期:2014-05-18 浏览次数:20707 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [id] int, [user_code] int, [card_id] int, [user_name] varchar(6), [record_date] date, [event_time] time(2), [WeekName] varchar(5), [Reason] sql_variant ) go insert [test] select 50102,56,13587426,'王玲玲','2012-5-29','7:20:57','二',null union all select 50101,56,13587426,'王玲玲','2012-5-29','7:20:52','二',null union all select 50168,56,13587426,'王玲玲','2012-5-29','17:11:54','二',null union all select 50169,56,13587426,'王玲玲','2012-5-29','17:11:58','二',null union all select 50207,56,13587426,'王玲玲','2012-5-30','7:23:31','三',null union all select 50263,56,13587426,'王玲玲','2012-5-30','17:02:43','三',null union all select 50310,56,13587426,'王玲玲','2012-5-31','7:19:25','四',null union all select 50389,56,13587426,'王玲玲','2012-5-31','17:23:24','四',null union all select 19394,6014,15656386,'王學燕','2011-9-6','17:55:50','二',null union all select 19421,6014,15656386,'王學燕','2011-9-7','7:51:42','三',null go with t as( select px=ROW_NUMBER()over(partition by [record_date],[user_name],[user_name],[WeekName] order by [record_date],[event_time] asc), * from test ), m as( select px=ROW_NUMBER()over(partition by [record_date],[user_name],[user_name],[WeekName] order by [record_date],[event_time] desc), * from test ) select id,user_code,card_id,user_name,record_date,event_time,WeekName,Reason from t where px=1 union select id,user_code,card_id,user_name,record_date,event_time,WeekName,Reason from m where px=1 /* id user_code card_id user_name record_date event_time WeekName Reason 19394 6014 15656386 王學燕 2011-09-06 17:55:50.00 二 NULL 19421 6014 15656386 王學燕 2011-09-07 07:51:42.00 三 NULL 50101 56 13587426 王玲玲 2012-05-29 07:20:52.00 二 NULL 50169 56 13587426 王玲玲 2012-05-29 17:11:58.00 二 NULL 50207 56 13587426 王玲玲