使用另一个表中的相应列值更新一个表中的列

时间:2013-08-27 11:13:04

标签: sql sql-server tsql

这个问题与我之前的问题有关:

Updating only ID's with the latest date SQL (2 of 6)

我有以下2个表格:

Table1 and Table2

我已经有了这个查询,它更新了Table1中只找到最新日期的ID。 但是,是否可以根据日期将Table1上的相应ID与表2中的相应ID进行匹配。

请参阅下面的查询:

Update Dairy 
SET DY_H_ID = (
              SELECT MAX(ID) 
              FROM History 
              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 Dairy)

我想做这样的事情以配合其余部分,但这不起作用:

AND SUBSTRING(CAST(DY_Date AS varchar(11)), 1, 10) = (SELECT SUBSTRING(CAST(H_DateTime AS varchar(11)), 1, 10) FROM History)

E.g。表1中的ID 10029应从历史记录中获得ID 3205。 ID 10030应该获得3206的ID,ID 10031应该获得ID 3207,ID 10032应该获得3208等等。

请注意,两个表中的值都会发生变化。

3 个答案:

答案 0 :(得分:1)

你能否使用DATEPART来解决这个http://msdn.microsoft.com/en-us/library/ms174420.aspx

UPDATE Dairy 
SET DY_H_ID = (
          SELECT MAX(ID) 
          FROM History 
          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 Dairy)

AND DATEPART(yyyy, DY_Date) = DATEPART(yyyy, H_DateTime)
AND DATEPART(mm, DY_Date) = DATEPART(mm, H_DateTime)
AND DATEPART(dd, DY_Date) = DATEPART(dd, H_DateTime)

答案 1 :(得分:1)

我无法确切地知道你想要什么:-(但是这个查询应该指向正确的方向:

UPDATE D 
SET    D.DY_H_ID = H.ID 
FROM   DAIRY D 
       INNER JOIN HISTORY H 
               ON Cast(D.DY_DATE AS VARCHAR(11)) = Cast( 
                  H.H_DATETIME AS VARCHAR(11)) 
WHERE  DY_H_ID IS NULL 
       AND DY_IDX IS NOT NULL 

UPDATE查询使用JOIN来比较两个表之间的日期。我想这就是你要求的,对吧?

答案 2 :(得分:1)

我发现了!!感谢@Secret Squirrel和@Gidil指出我正确的方向。

;WITH cte AS (
    SELECT H_IDX, MAX(ID) MaxID, SUBSTRING(H_Description, 24, 10) AS [Date]
    FROM History
    WHERE H_HA_ID = 7 
          AND H_HSA_ID = 19 
          AND H_Description LIKE 'Diary item added for :%'
    GROUP BY H_IDX, H_DateTime, H_Description
)
Update Dairy 
SET DY_H_ID = MaxID
FROM Dairy 
INNER JOIN CTE ON cte.H_IDX = DY_IDX
WHERE DY_H_ID IS NULL 
AND DY_IDX IS NOT NULL
AND DATEPART(YYYY, DY_Date) = SUBSTRING(cte.[Date], 1, 4)
AND DATEPART(MM, DY_Date) = SUBSTRING(cte.[Date], 6, 2)
AND DATEPART(DD, DY_Date) = SUBSTRING(cte.[Date], 9, 2)

请随时查看并评论此内容。