如何在表格中填充错过的日期

时间:2018-06-15 09:54:34

标签: sql sql-server algorithm tsql

任务是填充表格中缺少的日期。日期应该在现有的跟随日期和之前的日期中间。

表格中的数据示例:

array_map

要解决此任务,我尝试执行以下查询:

+----------+-------------------------+
| EntityID |       createdDate       |
+----------+-------------------------+
|    23964 | 2010-12-02 01:15:39.417 |
|    23965 | 2013-01-23 23:55:41.770 |
|    23966 |                         |
|    23967 |                         |
|    23968 |                         |
|    23969 |                         |
|    23970 | 2008-12-31 17:03:09.260 |
|    23971 | 2010-02-18 05:03:17.460 |
+----------+-------------------------+

知道如何解决此问题吗?

2 个答案:

答案 0 :(得分:3)

您的更新语句中的子选择需要限定两个EntityID - 否则它是不明确的。以下查询将根据具有日期的最近实体更新每个空日期。

    UPDATE Entity
SET createdDate = DATEADD(SECOND, 
                    (SELECT TOP 1 entity.EntityID - em.EntityID FROM Entity em WHERE em.EntityID < (Entity.EntityID) AND em.createdDate IS NOT NULL ORDER BY EntityID DESC), 
                    (SELECT TOP 1 em.createdDate FROM Entity em WHERE em.EntityID < (Entity.EntityID) AND em.createdDate IS NOT NULL ORDER BY EntityID DESC))
WHERE createdDate IS NULL;

答案 1 :(得分:0)

DECLARE @id INT,
@create_date DATETIME

    DECLARE upadte_records CURSOR FOR SELECT EntityID, createdDate from Entity
    OPEN upadte_records
    FETCH NEXT FROM upadte_records INTO @id, @create_date
    WHILE @@fetch_status <> -1
    BEGIN

            IF @create_date IS NULL
            BEGIN

                UPDATE Entity
                SET createdDate = DATEADD(SECOND, 1, (SELECT em.createdDate FROM Entity em WHERE em.EntityID = @id -1))
                WHERE EntityID = @id
            END


            FETCH NEXT FROM upadte_records INTO @id, @create_date
    END
    CLOSE upadte_records
    DEALLOCATE upadte_records