sql更新优先级基于给定的值

时间:2018-01-24 20:09:22

标签: sql

我有以下carRepair表

car     repair  repair_date   
toyota  breaks  1/3/2018
toyota  motor   1/2/2018
toyota  brakes  1/1/2018
mazada  lights  1/2/2017
mazda   brakes  1/1/2017

我需要添加一个包含汽车先前最差修复的列,基于:

最糟糕的修复

  1. motor
  2. 制动器
  3. 像这样的东西

    car    repair repair_date worst_repair
    toyota breaks 1/3/2018    motor
    toyota motor  1/2/2018    motor
    toyota breaks 1/1/2018    breaks
    mazda  lights 1/2/2017    breaks
    mazda  breaks 1/1/2017    breaks
    

    目前我正在逐一进行更新,例如:

     update cr set cr.worst_repair = cr2.repair 
     from 
         carRepair cr inner join 
         carRepair cr2 on 
                cr.car = cr2.car and 
                cr.repair_date >= cr2.repair_date
    where
        cr2.repair = 'lights'
    

    然后

     update cr set cr.worst_repair = cr2.repair 
     from 
         carRepair cr inner join 
         carRepair cr2 on 
                cr.car = cr2.car and 
                cr.repair_date >= cr2.repair_date
    where
        cr2.repair = 'breaks'
    

    最后

     update cr set cr.worst_repair = cr2.repair 
     from 
         carRepair cr inner join 
         carRepair cr2 on 
                cr.car = cr2.car and 
                cr.repair_date >= cr2.repair_date
    where
        cr2.repair = 'motor'
    

    是否有一种更有效的方式,而不是一个一个地做这个?

    为了澄清,打破覆盖灯,电机覆盖所有这些。

    谢谢

2 个答案:

答案 0 :(得分:1)

在SQL-SERVER中使用TOP 1和Outer Apply并按优先级排序

在这里演示http://rextester.com/live/UTOV54697

declare @carRepair table (car varchar(10),repair varchar(20), repair_date date, worst_repair varchar(20) null)

insert into @carRepair (car,repair,repair_date)
values 
('toyota','brakes','1/3/2018'),
('toyota','motor','1/2/2018'),
('toyota','brakes','1/1/2018'),
('mazda','lights','1/2/2017'),
('mazda','brakes','1/1/2017')

select * from @carRepair


update c1
set worst_repair = isnull(x.repair,c1.repair)
from @carRepair c1
outer apply (
select top 1 c2.repair
from @carRepair c2
where c2.car = c1.car
and c1.repair_date >= c2.repair_date
order by
(case c2.repair when 'motor' then 1 when 'brakes' then 2 else 3 end)
) x


select * from @carRepair

答案 1 :(得分:1)

这是一个可扩展的解决方案,使用定义不同修复及其严重性的表格:

create table repairTypes (severity integer, description varchar(30));
# should make severity unique

insert into repairTypes values (1, 'lights'), (2, 'breaks'), (3, 'motor');

update carRepair cr
set worst_repair = (
  select rt.description from repairTypes rt
  where rt.severity = (
    select max(rt2.severity) as max_severity
     from carRepair cr2 
       inner join repairTypes rt2 on cr2.repair=rt2.description
     where cr2.car=cr.car
     and cr2.repair_date <= cr.repair_date
  )
);