我有一张桌子,上面列出了产品级别的商机历史。如果机会有3个产品,则此机会将有3行条目。如下所示:
AccNum OppNum Product SnapshotDate NextStep
1 1 AAA 2019-04-02 Reach out and gauge interest
2 1 CCC 2019-04-02 Decision on hold due to paperwork
2 1 CCC 2019-03-31 NULL
2 1 CCC 2019-03-24 NULL
2 2 AAA 2019-04-02 Bid May. Discuss details w/ Vela
2 2 BBB 2019-04-02 Bid May. Discuss details w/ Vela
2 2 AAA-Inst. 2019-04-02 Bid May. Discuss details w/ Vela
2 2 AAA 2019-03-31 Bid May
2 2 BBB 2019-03-31 Bid May
2 2 AAA-Inst. 2019-03-31 Bid May
目标是提取先前的SnapshotDate和先前的NextStep,以查看NextStep中的值在最新快照和之前的快照之间是否已更改。
理想的表是这样的(我想对SnapshotDate做NextStep Column那样,我无法在论坛页面上显示出来)
AccNum OppNum Product SnapshotDate SnapshotDatePrev
1 1 AAA 2019-04-02 2019-03-31
2 1 CCC 2019-04-02 2019-03-31
2 1 CCC 2019-03-31 2019-03-24
2 1 CCC 2019-03-24 2019-03-17
2 2 AAA 2019-04-02 2019-03-31
2 2 BBB 2019-04-02 2019-03-31
2 2 AAA-Inst. 2019-04-02 2019-03-31
2 2 AAA 2019-03-31 2019-03-24
2 2 BBB 2019-03-31 2019-03-24
2 2 AAA-Inst. 2019-03-31 2019-03-24
这就是我所做的。我无法正确拉出以前的SnapshotDate。我只能使用Lead函数在当前行之前拉行。我无法根据产品数量来处理每个条目的多个行。 (请参阅AccNum:2 OppNum:2)
create table GTM.dbo.Table_History
(
AccNum int,
OppNum int,
Product nvarchar(50),
SnapshotDate date,
NextStep nvarchar(150)
)
insert into GTM.dbo.Table_History
values
(1,1,'AAA','2019-04-02','Reach out and gauge interest'),
(2,1,'CCC','2019-04-02','Decision on hold due to paperwork'),
(2,1,'CCC','2019-03-31',NULL),
(2,1,'CCC','2019-03-24',NULL),
(2,2,'AAA','2019-04-02','Bid May. Discuss details w/ Vela'),
(2,2,'BBB','2019-04-02','Bid May. Discuss details w/ Vela'),
(2,2,'AAA-Inst.','2019-04-02','Bid May. Discuss details w/ Vela'),
(2,2,'AAA','2019-03-31','Bid May'),
(2,2,'BBB','2019-03-31','Bid May'),
(2,2,'AAA-Inst.','2019-03-31','Bid May')
SELECT *
FROM(
SELECT
AccNum
,OppNum
,Product
,convert(DATE,DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1)) AS PrevSun
,SnapshotDate
,lead(SnapshotDate) OVER (PARTITION BY AccNum, OppNum ORDER BY SnapshotDate DESC) AS SnapshotDatePrev
,NextStep
,lead(NextStep) OVER (PARTITION BY AccNum, OppNum ORDER BY SnapshotDate DESC) AS NextStepprev
FROM GTM.DBO.Table_History) t1
WHERE t1.SnapshotDatePrev>=t1.PrevSun
任何指导将不胜感激。谢谢!