仅使用最新日期SQL更新ID(2/6)

时间:2013-08-27 09:48:44

标签: sql sql-server tsql

我有以下表格:

Table 1

Table 2

我制定了这个查询:

Update Table 1 
SET DY_H_ID = ( 

    SELECT MAX(ID) 
    FROM Table 2
    WHERE H_DateTime <= DY_Date 
    AND H_IDX = DY_IDX 
    AND H_HA_ID = 7 
    AND H_HSA_ID = 19 
    AND H_Description LIKE 'Diary item added for :%'

) 
WHERE DY_H_ID IS NULL AND DY_IDX IS NOT NULL

结果如下:

Table 1 after Update

但是,此查询会更新所有6行。我只需要更新具有最新日期的两行,即'2013-08-29 15:00:00.000'。这意味着6条记录中只有2条会被更新,而其他4条记录将保持为NULL。

如何通过添加上述查询来完成此操作?我知道这可能不太理想,但除了做这样的事情之外别无选择。我不明白的是你如何选择最新的日期而不用硬编码。这些数据可能会发生变化,但并不总是相同的日期等。

3 个答案:

答案 0 :(得分:1)

只需在以下位置添加其他条件:

Update Table 1 
SET DY_H_ID = ( 

    SELECT MAX(ID) 
    FROM Table 2
    WHERE H_DateTime <= DY_Date 
    AND H_IDX = DY_IDX 
    AND H_HA_ID = 7 
    AND H_HSA_ID = 19 
    AND H_Description LIKE 'Diary item added for :%'

) 
WHERE DY_H_ID IS NULL AND DY_IDX IS NOT NULL
and DY_Date = (select max(DY_Date) from Table 1)

答案 1 :(得分:1)

试试这个:

UPDATE TABLE 1 
SET    DY_H_ID = (SELECT Max(ID) 
                  FROM   TABLE 2 
                  WHERE  H_DATETIME <= DY_DATE 
                         AND H_IDX = DY_IDX 
                         AND H_HA_ID = 7 
                         AND H_HSA_ID = 19 
                         AND H_DESCRIPTION LIKE 'Diary item added for :%') 
WHERE  DY_H_ID IS NULL 
       AND DY_IDX IS NOT NULL 
       AND DY_DATE = (SELECT Max(DY_DATE) 
                      FROM   TABLE1) 

答案 2 :(得分:1)

使用CTE,与SQL-Server-2005或更高版本兼容

;WITH cte AS (
    SELECT H_IDX, MAX(ID) MaxID
    FROM Table2
    WHERE H_HA_ID = 7 
          AND H_HSA_ID = 19 
          AND H_Description LIKE 'Diary item added for :%'
    GROUP BY H_IDX
)
Update Table1 
SET DY_H_ID = MaxID
FROM Table1 
INNER JOIN CTE ON cte.H_IDX = DY_IDX
WHERE DY_H_ID IS NULL