我想更新从当前日期和原始日期之间的最早开始日期开始的日期。我的查询是:
update TableA
set [Stop_Date] =DATA.Min_Start
FROM TableA
JOiN
(select min(TableB.START_DTTM ) as Min_Start
from TableB
where
TableB.CancelReason ='Treatment' AND
TableA.Start_Date>=TableB.START_DTTM AND
TableB.START_DTTM '< GETDATE()
) DATA
ON TableA.Ref_No=TableB.REFRL_REFNO
where
[Stop_Date] is null
但是TableA.Start_Date
似乎会导致问题。任何人都可以帮助正确的SQL吗?
以下是一些测试数据:
DECLARE @TableA TABLE (Ref_No Int, Stop_Date DateTime,Start_Dat DateTime)
DECLARE @TableB TABLE (REFRL_REFNO int, CancelReason varchar(50), START_DTTM DateTime,
Stop_DTTM DateTime,Comments varchar(50))
insert @TableA
select 1, '10 jan 2000', '5 jan 2000'
insert @TableA
select 4, NULL, '9 jan 2000'
insert @TableB
select 1,'Treatment','8 Jan 2000','9 Jan 2000','Shouldn''t be used'
insert @TableB
select 4,'Treatment','1 Jan 2000','2 Jan 2000','Shouldn''t be used'
insert @TableB
select 4,'Treatment','21 Jan 2000','22 Jan 2000','Shouldn''t be used'
insert @TableB
select 4,'Treatment','11 Jan 2000','12 Jan 2000','Should be used'
insert @TableB
select 4,'Other','10 Jan 2000','11 Jan 2000','Shouldn''t be used'
答案 0 :(得分:1)
您的情况TableA.Start_Date>=TableB.START_DTTM AND TableB.START_DTTM '< GETDATE()
是错误的。这将TableB值限制为startdate之前的值,小于当前日期的值,而不是两者之间的值。
以下似乎有效。
UPDATE TableA
SET Stop_Date =
(
SELECT MIN(TableB.START_DTTM)
FROM TableB
WHERE
TableA.Ref_No = TableB.REFRL_REFNO
AND (TableB.CancelReason = 'Treatment')
AND (TableB.START_DTTM BETWEEN TableA.[Start_Date] AND GETDATE())
)
WHERE (TableA.Stop_Date IS NULL)