我有一个'source'表,其中包含用户登录列表以及登录日期和时间。 'source'表格看起来像这样......
CREATE TABLE [dbo].[tblSrc](
[userID] [varchar](50) NULL,
[date] [datetime] NULL)
为了便于说明,某些行可能包含......
userID date
------ ----
1 2013-01-01 00:00:00.000
2 2013-01-01 00:00:00.000
3 2013-01-01 00:00:00.000
2 2013-01-02 00:00:00.000
3 2013-01-03 00:00:00.000
3 2013-01-04 00:00:00.000
1 2013-01-02 00:00:00.000
3 2013-01-05 00:00:00.000
我有一个'目的地'表如下......
CREATE TABLE [dbo].[tblDest](
[userID] [varchar](50) NOT NULL,
[date1] [datetime] NULL,
[date2] [datetime] NULL,
[date3] [datetime] NULL)
源表中的userID包含多个重复的userID,而我已使用唯一的userID填充目标表。
我需要做的是通过源表进行迭代并为每个用户插入最后三个登录日期?
因此,举例来说,目标表使用userID'3'
用户'3'在源表中有4个条目
userID date1 date2 date3
------ ----- ----- -----
3 2013-01-05 00:00:00.000 2013-01-04 00:00:00.000 2013-01-03 00:00:00.000
date1是最近的登录日期,date2然后是next,date3是下一个。
我可以从每个用户ID的源表中获取最新日期,但我无法弄清楚如何获取最近的三个(假设有三个日期)并将它们插入到目标表中。
非常感谢任何帮助。
答案 0 :(得分:1)
这个SQL应该可以工作:
with userrows as
(SELECT t.userID, t.date,
ROW_NUMBER() OVER(PARTITION BY t.userID ORDER BY t.date DESC) AS Row
FROM tblSrc t)
insert into tblDest
select distinct
u.userID,
(select top 1 date from userrows u1 where u1.userID=u.userID and u1.Row=1 ) 'date1',
(select top 1 date from userrows u2 where u2.userID=u.userID and u2.Row=2) 'date2',
(select top 1 date from userrows u3 where u3.userID=u.userID and u3.Row=3) 'date3'
from userrows u
要添加状态,您可以执行以下操作:
with userrows as
(SELECT t.userID, t.date,t.status,
ROW_NUMBER() OVER(PARTITION BY t.userID ORDER BY t.date DESC) AS Row
FROM tblSrc t)
insert into tblDest
select distinct
u.userID,
(select date from userrows u1 where u1.userID=u.userID and u1.Row=1 ) 'date1',
(select status from userrows u1 where u1.userID=u.userID and u1.Row=1 ) 'status1',
(select date from userrows u2 where u2.userID=u.userID and u2.Row=2) 'date2',
(select status from userrows u2 where u2.userID=u.userID and u2.Row=2 ) 'status2',
(select date from userrows u3 where u3.userID=u.userID and u3.Row=3) 'date3',
(select status from userrows u3 where u3.userID=u.userID and u3.Row=3 ) 'status3'
from userrows u