[英]How to filter a column based on values of another column in SQL
我需要在現有表中建立一個新列。 因此,有兩列,“ cmg”和“ effdate”,我需要創建一個名為“ enddate”的新列。 因此,對於特定的cmg,eff_date =當前日期的最大值,下一行中的日期應等於上一行中的日期-1。
例如,
cmg | effdate
1 23/10/2018
1 1/10/2018
1 1/1/2018
3 1/12/2018
3 1/3/2018
我需要首先基於cmg列中的值過濾行,然后獲取enddate,如下所示:
cmg | effdate | enddate
1 23/10/2018 currentdate
1 1/10/2018 22/10/2018
1 1/1/2018 30/9/2018
3 1/12/2018 currentdate
3 1/3/2018 30/11/2018
使用LEAD和OVER
SELECT cmg, effdate, LEAD(DATEADD(DAY, -1, effdate),1, getdate()) OVER (PARTITION BY cmg ORDER BY effdate ASC) as enddate
FROM testcmg
ORDER BY cmg, effdate DESC
以下查詢應執行您想要的操作:
CREATE TABLE #temp (cmg INT, effdate DATE)
INSERT INTO #temp VALUES
(1,'2018-10-23'),
(1,'2018-10-01'),
(1,'2018-01-01'),
(3,'2019-03-01'),
(3,'2018-12-01')
SELECT cmg, effdate, LAG(DATEADD(DAY,-1,effdate),1, GETDATE()) OVER (PARTITION BY cmg ORDER BY effdate DESC) as enddate
FROM #temp
ORDER BY cmg, effdate DESC
結果如下
cmg effdate enddate
1 2018-10-23 2019-06-11
1 2018-10-01 2018-10-22
1 2018-01-01 2018-09-30
3 2019-03-01 2019-06-11
3 2018-12-01 2019-02-28
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.