[英]Adding a Date column based on the next row date value
我正在使用SQL Server 2005.从下面的tbl_temp表中,我想基于下一行的StartDate减去1天添加一个EndDate列,直到AID和UID组合发生变化。 此计算的EndDate将作为EndDate转到它上面的行。 AID和UID组的最后一行将获得系统日期作为其EndDate。 该表必须按AID,UID,StartDate顺序排序。 谢谢您的帮助。
- tbl_temp
AID UID StartDate 1 1 2013-02-20 2 1 2013-02-06 1 1 2013-02-21 1 1 2013-02-27 1 2 2013-02-02 1 2 2013-02-04
- 需要的结果
AID UID StartDate EndDate 1 1 2013-02-20 2013-02-20 1 1 2013-02-21 2013-02-26 1 1 2013-02-27 sysdate 1 2 2013-02-02 2013-02-03 1 2 2013-02-04 sysdate 2 1 2013-02-06 sysdate
最简单的方法是使用相关的子查询:
select t.*,
(select top 1 dateadd(day, -1, startDate )
from tbl_temp t2
where t2.aid = t.aid and
t2.uid = t.uid and
t2.startdate > t.startdate
) as endDate
from tbl_temp t
要获取当前日期,请使用isnull()
:
select t.*,
isnull((select top 1 dateadd(day, -1, startDate )
from tbl_temp t2
where t2.aid = t.aid and
t2.uid = t.uid and
t2.startdate > t.startdate
), getdate()
) as endDate
from tbl_temp t
通常,我会建议在isnull()
使用coalesce()
isnull()
。 但是,某些版本的SQL Server中存在一个错误,它会在第二个参数中评估第一个参数。 通常,这没有什么区别,但它有一个子查询。
最后,使用sysdate
让我想到了Oracle。 同样的方法也适用于那里。
;WITH x AS
(
SELECT AID, UID, StartDate,
ROW_NUMBER() OVER(PARTITION BY AID, UID ORDER BY StartDate) AS rn
FROM tbl_temp
)
SELECT x1.AID, x1.UID, x1.StartDate,
COALESCE(DATEADD(day,-1,x2.StartDate), CAST(getdate() AS date)) AS EndDate
FROM x x1
LEFT OUTER JOIN x x2 ON x2.AID = x1.AID AND x2.UID = x1.UID
AND x2.rn = x1.rn + 1
ORDER BY x1.AID, x1.UID, x1.StartDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.