[英]MySQL derive end date from two consecutive rows which only have start date
I have a table like the one below:我有一张像下面这样的表:
I have tried this, but it doesn't work:我试过这个,但它不起作用:
SELECT A.id, cast(A.startdate as date) as from_date, cast(B.startdate as date)
AS enddate
FROM three A INNER JOIN three B ON B.id = (A.id)
ORDER BY A.id,cast(A.startdate as date) ASC
My desired result should be:我想要的结果应该是:
I think this is what you want:我认为这就是你想要的:
SELECT
t.Id,
t.old_value,
t.new_value,
t.StartDate,
-- if it's the latest entry of distinct old_value new_value pairs
IF(t1.Id IS NULL, t2.StartDate - INTERVAL 1 DAY, t.StartDate) AS EndDate
FROM three t
LEFT JOIN three t1 ON t.old_value = t1.old_value AND t.new_value = t1.new_value
AND t.StartDate > t1.StartDate
LEFT JOIN three t2 ON t.new_value = t2.old_value
;
Hard to tell without show creates and usable sample data.很难说不显示创建和可用的示例数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.