如何生成包含最新记录的摘要表

时间:2017-06-18 23:44:52

标签: sql sql-server

假设我有一个带有一些虚拟记录的动作表,如下所示:

create table action
(
userid int
,date datetime
,action varchar(5)
)

insert into action values(1, '2017-03-24 00:00:00','1')
insert into action values(2, '2017-03-24 00:00:00','2')
insert into action values(3, '2017-03-24 00:00:00','1')
insert into action values(4, '2017-03-24 00:00:00','2')
insert into action values(4, '2017-03-24 00:01:00','1')
insert into action values(5, '2017-03-24 00:00:00','1')

insert into action values(1, '2017-03-23 00:00:00','1')
insert into action values(2, '2017-03-23 00:00:00','1')
insert into action values(3, '2017-03-23 00:00:00','2')
insert into action values(4, '2017-03-23 00:00:00','1')
insert into action values(1, '2017-03-23 00:01:00','2')
insert into action values(2, '2017-03-23 00:02:00','2')
insert into action values(1, '2017-03-23 00:03:00','1')
insert into action values(2, '2017-03-23 00:05:00','1')

我想生成一个摘要表,以便每个用户显示当天的最新状态。结果如下。

create table summary
(
userid int
,date datetime
,status varchar(5)
)

date    userid  status
2017-03-24  1   1
2017-03-24  2   2
2017-03-24  3   1
2017-03-24  4   1
2017-03-24  5   1
2017-03-23  1   1
2017-03-23  2   1
2017-03-23  3   2
2017-03-23  4   1

我尝试使用row_number()(按用户ID顺序按日期desc分区) 但结果并不像预期的那样。

请帮忙吗? 我正在使用sql server,但欢迎使用任何数据库语法!

2 个答案:

答案 0 :(得分:0)

您需要按日期进行分区:

select a.*
from (select a.*, 
             row_number() over (partition by a.userid, cast(a.date as date)
                                order by a.date desc
                               ) as seqnum
      from action a
     ) a
where seqnum = 1

答案 1 :(得分:0)

你可以使用它。

INSERT INTO [summary]
SELECT a.userid
,DATEADD(dd, 0, DATEDIFF(dd, 0, [date]))
, a.[action] 
FROM [action] a
WHERE a.[date] IN 
(
SELECT MAX([date]) 
FROM [action] a1 WHERE a.userid = a1.userid 
GROUP BY userid, DATEADD(dd, 0, DATEDIFF(dd, 0, [date]))
)