Sql 基于不同表的两列更新整列
我向表中添加了一个新列。表中的列为:Sql 基于不同表的两列更新整列,sql,sql-server-2005,datetime,Sql,Sql Server 2005,Datetime,我向表中添加了一个新列。表中的列为: Identifier(unique identity but not joinable to the other table) ClinicalID(int) senttime(datetime) orgID(int-new column) 我需要根据发送时间从不同的表中更新新列。 我应该检查发送时间的日期范围,并相应地更新orgID。 另一个表的列: ClinicalIDentifier org ID(int) old orgID(int) effec
Identifier(unique identity but not joinable to the other table)
ClinicalID(int)
senttime(datetime)
orgID(int-new column)
我需要根据发送时间从不同的表中更新新列。
我应该检查发送时间的日期范围,并相应地更新orgID。
另一个表的列:
ClinicalIDentifier
org ID(int)
old orgID(int)
effectivefromtime
effectivethrutime
我面临的问题是,如果另一个表的senttime为>生效fromtime,它将显示同一个ClinicalID的其他组织ID,其中senttime为>生效fromtime
我一直在比较日期范围
如果您需要任何进一步的信息,请告诉我
WITH CTE AS
(
SELECT
FirstTable.OrgID NewOrgID,
SecondTable.OrgID
FROM
FirstTable
LEFT JOIN SecondTable
ON FirstTable.ClinicalID = SecondTable.ClinicalIndetifier
AND FirstTable.SentTime > SecondTable.EffectiveFromTime
AND FirstTable.SentTime < SecondTable.EffectiveThruTime
)
UPDATE CTE
SET NewOrgID = OrgID
我无法从您的问题中分辨出表名是什么,或者它们是如何连接的,但我认为应该这样做。要测试CTE,您应该将上面的整个UPDATE语句替换为SELECT*FROM CTE,这将为每个NewOrgID显示NULL,OrgID将为您显示将在每行中填充的值。如果您真的想确定您可以修改CTE,使其包含FirstTable和SecondTable中的所有列。明白了
select
case when (effectivethrutime is null and senttime >= effectivefromtime) then orgid
when (effectivethrutime is not null and senttime >= effectivefromtime) then orgID
when (effectivethrutime is not null and senttime between effectivethrutime and effectivefromtime) then orgid
end as orgid
from ac
left join op
on ac.clinicalidentifier=op.clinicalidentifier
where ac.senttime>op.effectivefromtime
and ac.senttime<=isnull(op.effectivethrutime,ac.senttime)
到目前为止,这是可行的。
如果我需要更正,请告诉我。
谢谢
vihar你试过中间人吗?有效FromTime和有效ThruTime之间的senttime是。我试过了。还是一样。它还接受小于该值的值,并在使用between查询时显示空值。我要查找的是,如果sentdate位于两个Other日期列之间,则org Id else old org Id。。。我使用了case语句:codecase when op.effectivethrutime不为null,ac.senttime在op.effectivefromtime和op.effectivethrutime之间,然后是op.organizationidentifier when op.effectivethrutime不为null,ac.senttime