比较两个字段,根据结果更新其中一个字段

时间:2017-01-11 14:55:53

标签: sql-server

我有多个joins的查询。我需要将一个table的字段与一秒的字段进行比较。如果第一个字段小于另一个字段,我需要用第二个字段覆盖第一个字段。可以使用case或if语句来完成吗?查询提取数据然后创建一行中包含多行的结果集。 PK是unique_key,linex

示例:

unique_key,line1,person_id,service_date,amount          unique_key,line2,person_id,service_date,amount          unique_key,line3,person_id,service_date,amount

Select t1.Unique_key, t1.linex, t1.person_id,t1.service_date, t1.amount,     t2.service_date, t2.amount, t3.service_date, t3.amount
  from tbl1   t1
  left join tbl2  t2
    on t1.unique_key = t2.unique_key
  left join tbl3  t3
    on t1.unique_key = t3.unique_key

如果第二个服务日期大于第一个服务日期,我需要update第一个服务日期。

查询比这更复杂。

2 个答案:

答案 0 :(得分:0)

case when t2.service_date > t1.service_date 
     then t2.service_date 
     else t1.service_date 
end as service_date

或者我错过了什么?

答案 1 :(得分:0)

您需要重命名t1.service_date字段:

Select t1.Unique_key
, t1.linex
, t1.person_id
, iif(t2.service_date > t1.service_date, t2.service_date, t1.service_date) as [Overlayed_Service_Date] 
, t1.amount
, t2.service_date
, t2.amount
, t3.service_date
, t3.amount 
from tbl1 t1 
left join tbl2 t2 on t1.unique_key = t2.unique_key 
left join tbl3 t3 on t1.unique_key = t3.unique_key
相关问题