我有OppTable
ID actualclosedate status
--------------------------------------
1 10-March Won
2 11-June Lost
3 13-July Open
我有阶段变化
--------------------------------------
ID stage createdon
--------------------------------------
1 Propsect 1-Jan
1 Qualify 15-Jan
1 Develop 25-Jan
2 Qualify 9-Feb
2 Develop 7-March
3 Prospect 9-April
3 Prospect 9-April
如何填充基于多个条件生成的新列中的NULL值。 例如:如果Opp是WON / LOST,则关闭日期 如果Opp是Open,请将今日日期
预期结果:
--------------------------------------
OppID Stage createdon newcolumn
--------------------------------------
1 Propsect 1-Jan 15-Jan
1 Qualify 15-Jan 25-Jan
1 Develop 25-Jan 10-March ---(closedate for Wonn Opp1)
2 Qualify 9-Feb 7-March
2 Develop 7-March 11-june ---(closedate for lost Opp2)
3 Prospect 9-April 10-April
3 Qualify 10-April 4/2/2017----(todaydate for Open Opp3)
使用此查询,将获得我打开的实际关闭日期,但我想要今天日期
Select *
,NewColumn = COALESCE(Lead(A.createdon) over (Partition By A.ID Order By A.CreatedOn),B.actualclosedate)
From stagechange A
Join OppTable B on A.ID=B.ID
答案 0 :(得分:2)
您可以尝试此查询:
WITH cte AS (
SELECT a.ID, a.Stage, a.CreatedOn, b.CloseDate, b.Status,
LEAD(a.CreatedOn) OVER (PARTITION BY a.ID ORDER BY a.CreatedOn) ld,
ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) rn,
DENSE_RANK() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) dr
FROM stagechange a
INNER JOIN OppTable b
ON a.ID = b.ID
)
SELECT t.ID, t.Stage, t.CreatedOn,
CASE WHEN (t.rn <> 1 OR t.rn = t.dr) AND t.ld IS NOT NULL THEN t.ld
WHEN t.Status <> 'Open' THEN t.CloseDate
ELSE GETDATE()
END AS newcolumn
FROM cte t
ORDER BY t.ID, t.CreatedOn;
我发现同时使用ROW_NUMBER()
和DENSE_RANK()
来处理给定ID
可以有多个等效结束日期的边缘情况是必要的。在这种情况下,我们需要一些方法来确定哪一个是最老的。
<强>输出:强>
在这里演示: