我已经尝试过搜索,但没有什么能与我想要的完全匹配,所以任何帮助都会受到赞赏!
我有一张如下表:
+-----------+---------------+-------+------------+
| Policy_NO | Creation_Date | Limit | Limit_Date |
+-----------+---------------+-------+------------+
| A00001 | 8/31/2015 | 1000 | 8/31/2015 |
| A00001 | 8/31/2015 | 2000 | 9/30/2015 |
| A00001 | 8/31/2015 | 5000 | 10/22/2015 |
| A00001 | 8/31/2015 | 500 | 11/17/2015 |
| A00003 | 9/21/2015 | 3000 | 1/1/2016 |
+-----------+---------------+-------+------------+
我想要的是拥有一个' End_Limit_Date'它应该是具有相同策略编号-1的下一个限制的日期,或者距创建日期恰好一年。
例如,上表应为:
+------------------------------------------------+----------------+
| Policy_NO Creation_Date Limit Limit_Date | End_Limit_Date |
+------------------------------------------------+----------------+
| A00001 8/31/2015 1000 8/31/2015 | 9/29/2015 |
| A00001 8/31/2015 2000 9/30/2015 | 10/21/2015 |
| A00001 8/31/2015 5000 10/22/2015 | 11/16/2015 |
| A00001 8/31/2015 500 11/17/2015 | 8/31/2016 |
| A00003 9/21/2015 3000 1/1/2016 | 9/21/2016 |
+------------------------------------------------+----------------+
我只有只读权限,因此更新查询'并且'创建新表'查询不适用于我的情况...
提前感谢您的帮助!
答案 0 :(得分:1)
如果您有SQL Server 2012或更高版本,则可以使用LEAD()
获取下一行:
SELECT t.Policy_NO,
t.Creation_Date,
t.Limit,
t.Limit_Date,
End_Limit_Date = ISNULL(
DATEADD(DAY, -1, LEAD(t.Limit_Date) OVER(PARTITION BY t.Policy_NO
ORDER BY t.Limit_Date)),
DATEADD(YEAR, 1, t.Creation_Date))
FROM dbo.T;
如果没有,您将需要一个相关的子查询:
SELECT t.Policy_NO,
t.Creation_Date,
t.Limit,
t.Limit_Date,
End_Limit_Date = ISNULL(
DATEADD(DAY, -1, t2.Limit_Date),
DATEADD(YEAR, 1, t.Creation_Date))
FROM dbo.T
OUTER APPLY
( SELECT TOP 1 t2.Limit_Date
FROM dbo.T AS t2
WHERE t2.Policy_NO = t.Policy_NO
AND t2.Limit_Date > t.Limit_Date
ORDER BY t2.Limit_Date
) AS t2;