更新SQL中最早的记录?

时间:2012-11-22 09:24:51

标签: sql

我有一个问题,我想在我的表中更新一个名为Service_Log_Temp的作业的最早条目,其中duplicate ='No',其余的是duplicate ='Yes'

此刻我的桌子是:

http://s15.postimage.org/gulifcaiz/Current_Table.jpg

所以我想要一个查看K_B_Job_No的脚本(你会看到我在这里列出了2个不同的作业)并根据L1_GA_SR_Creation_Date&更新最早的条目。 L2_B_Start_time_Of_Activity with Duplicate ='No',其余为Duplicate ='Yes'。

这应该是它的样子:

http://s14.postimage.org/h7zx5xgj5/Desired_Table.jpg

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

试试这个

select key_service,k_r_job_no,L1_GA_SR_Creation_Date,L2_B_Start_time_Of_Activity,
   case 
    when (select min(L1_GA_SR_Creation_Date) and min(L2_B_Start_time_Of_Activity)
       then 'No'
      else 'Yes'
  end as Duplicate
from Service_Log_Temp
group by k_r_job_no

答案 1 :(得分:0)

;with a as (select K_B_Job_No, min(L1_GA_SR_Creation_Date + cast(L2_B_Start_time_Of_Activity as datetime)) as dttime from Service_Log_Temp
group by K_B_Job_No)
select key_service,K_B_Job_No,L1_GA_SR_Creation_Date,L2_B_Start_time_Of_Activity, 
(case when
(select dttime from a where a.K_B_Job_No=b.K_B_Job_No)=(L1_GA_SR_Creation_Date + cast(L2_B_Start_time_Of_Activity as datetime))
then 'NO' else 'YES' end) as Duplicate
from Service_Log_Temp b

答案 2 :(得分:0)

这应该适用于postgres,其中连接是|| - 您必须将其更改为系统中的串联

背景:找到每个工作第一次运行的时间:

select k_r_job_no,min( L1_GA_SR_Creation_Date+L2_B_Start_time_Of_Activity) from
service_log_temp
group by k_r_job_no

问题在于我们无法从此查询中获取ID ...

但我们可以将其用作子查询。由于通常不可能从子查询中获取多行,我们必须进行连接以获得每个作业的正确时间:(您可能需要进行类型转换以使串联起作用)

select key_service from service_log_temp where 
   k_r_job_no||L1_GA_SR_Creation_Date+L2_B_Start_time_Of_Activity in( 
     select k_r_job_no||min( L1_GA_SR_Creation_Date+L2_B_Start_time_Of_Activity) 
       from service_log_temp
        group by k_r_job_no
     )

这可以改写为更新:

update service_log_temp set Duplicate='Yes' where 
   k_r_job_no||L1_GA_SR_Creation_Date+L2_B_Start_time_Of_Activity in( 
     select k_r_job_no||min( L1_GA_SR_Creation_Date+L2_B_Start_time_Of_Activity) 
       from service_log_temp
        group by k_r_job_no
     )

之后

 update service_log_temp set Duplicate='No' where Duplicate is null

(或者,如果你想在一个查询中使用SRIRAM,请使用“case”)