0

我有以下表格:

表格1

和:

表 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

结果是:

更新后的表1

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

如何通过添加到上述查询来做到这一点?我知道这可能并不理想,但别无选择,只能做这样的事情。我不明白的是你如何只选择最新的日期而不进行硬编码。此数据可能会更改,并且不会总是相同的日期等。

4

3 回答 3

1

只需在 where 中添加另一个条件:

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)
于 2013-08-27T09:56:32.460 回答
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) 
于 2013-08-27T09:56:49.233 回答
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 
于 2013-08-27T10:01:55.797 回答