简体   繁体   English

MySQL 从只有开始日期的两个连续行中导出结束日期

[英]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.

相关问题 当结果仅保留属性有效的开始日期时,如何在两个日期之间进行MySQL查询? - How to MySQL query between two dates when the result holds only the start date from which the attribute is valid? 从MySql中抓取当前日期在开始日期和结束日期之间的行(检查当前日期是否在开始日期和结束日期之间) - Grabbing rows from MySql where current date is in between start date and end date (Check if current date lies between start date and end date) mysql开始日期和结束日期 - mysql start date and end date MySQL按连续日期选择行 - mysql select rows by consecutive date MySQL:开始日期和结束日期之间的正确日期范围为两个字段 - MySQL: Proper date range between start and end date as two fields 是否有任何MySQL函数可以获取开始日期或结束日期在给定开始日期和结束日期之间的所有行? - 第2部分 - Are there any MySQL functions to get all rows with with a start or end date that fall between a given start and end date? - Part 2 是否有任何MySQL函数可以获取开始日期或结束日期在给定开始日期和结束日期之间的所有行? - Are there any MySQL functions to get all rows with with a start or end date that fall between a given start and end date? MySQL SELECT TMP行 - 开始日期和结束日期之间的日期 - MySQL SELECT TMP rows - DATES between Start and End date MySQL选择指定日期在开始日期和结束日期之间的行 - MySQL Select rows where specified date is between start date and end date MySQL - 比较开始和结束日期 - MySQL - Comparing start and end date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM