我有两个表,其中一个表有开始日期,另一个表有持续时间。表格值如下
TourID | StartDate | Tour Name
1 | 2016/5/10 | example name
2 | 2016/3/20 | Tour 2
PlaceTrip
TripID | Place ID | Duration(days) | TourID
1 | 1 | 5 | 1
2 | 2 | 7 | 1
3 | 3 | 2 | 1
4 | 1 | 10 | 2
5 | 2 | 4 | 2
预期/有用的查询结果是日期+持续时间=到达日期
TourID | PlacesID | Arrive Date
1 | 1 | 2016/5/15
1 | 2 | 2016/5/22 <-- this date will start from 2016/5/15 instead of 2016/5/10
1 | 3 | 2016/5/24
2 | 1 | 2016/3/30
2 | 2 | 2016/4/1
答案 0 :(得分:0)
您必须创建一个获取所有持续时间的子查询。
1)获取所有先前行的数据(在您的情况下,我假设的地点ID)并总结它们。
2)使用dateadd函数将每行的总和(地点ID)添加到初始开始日期(2016/5/10)。
这是一个例子(自己完成):
select CurrentPlace.PlaceID,
sum(CurrentPlace.Duration) as TotalDuration
from CurrentPlace,
PreviousPlaces
where PreviousPlaces.PlaceID <= SequencesAnalysis.PlaceID
group by CurrentPlace.RowID
答案 1 :(得分:0)
您可以使用window function为您提供累计持续时间:
SELECT TourID, TripID, PlaceID, Duration, SUM(Duration) OVER( PARTITION BY TripID ORDER BY PlaceID ) AS CumulativeDuration
FROM PlaceTrip
然后您需要做的就是将以上内容加入Tour表:
SELECT *
FROM (
SELECT TourID, TripID, PlaceID, Duration, SUM(Duration) OVER( PARTITION BY TripID ORDER BY PlaceID ) AS CumulativeDuration
FROM PlaceTrip ) AS PTCD
INNER JOIN Tour AS T ON PTCD.TourID = T.TourID
您需要使用DATEADD函数通过向StartDate添加“CumulativeDuration”来计算“到达日期”