Это просто ПРИСОЕДИНЕНИЕ, как
CREATE TABLE T1(
ID INT,
Name VARCHAR(45),
Date_Time DATETIME,
Flag INT
);
INSERT INTO T1 (ID, Name, Flag) VALUES
(1, 'Name1', 0),
(2, 'Name2', 1),
(3, 'Name3', 1);
CREATE TABLE T2(
ID INT,
Tb1Id INT,
Date_Time DATETIME
);
INSERT INTO T2 VALUES
(1, 1, '2017-09-20'),
(2, 1, '2018-01-09'),
(3, 2, '2016-09-01'),
(4, 2, '2015-09-02'),
(5, 3, '2016-09-06'),
(6, 3, '2019-09-10');
;WITH CTE AS
(
SELECT T1.ID,
T1.Name, --You can remove this cause I thought you want a SELECT
MAX( T2.Date_Time ) Date_Time
FROM T1 INNER JOIN T2
ON T1.Id = T2.Tb1Id
WHERE T1.Flag = 1
GROUP BY T1.ID,
T1.Name --And this one too
)
UPDATE T1
SET Date_Time = CTE.Date_Time
FROM T1 INNER JOIN CTE
ON T1.Id = CTE.Id;
SELECT *
FROM T1;
Возвращает:
+----+-------+---------------------+------+
| ID | Name | Date_Time | Flag |
+----+-------+---------------------+------+
| 1 | Name1 | | 0 |
| 2 | Name2 | 01/09/2016 00:00:00 | 1 |
| 3 | Name3 | 10/09/2019 00:00:00 | 1 |
+----+-------+---------------------+------+
Демонстрация в реальном времени