使用SQL中的子查询更新多行

时间:2011-11-18 09:40:09

标签: sql sql-server-2000 subquery sql-update

我有一个汇总表从主表返回数据。我试图从主表中的值更新一些摘要数据:

update #summary
  set TopSpeed = CD.TopSpeed, SpeedTime = CD.TimeSent, SpeedDriver = CD.Driver
from
(
  select top 1 TopSpeed, TimeSent, Driver
  from CarData
  where CarData.VehicleId = #summary.VehicleId 
  and CarData.TimeSent between #summary.Start and #summary.Stop
  order by CarData.TopSpeed desc, TimeSent desc
) as CD

#summary临时表正在创建有关汽车行程的汇总数据。每辆车可以有多次行程,每次行程都有开始和停止时间。 CarData表包含所有详细的汽车数据,如速度和位置等。

请帮忙吗?

谢谢, 罗伯特

2 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE
    #summary
SET
    #summary.TopSpeed = CarData.TopSpeed ,
    #summary.SpeedTime = CarData.SpeedTime 
    ...
FROM
    #summary
INNER JOIN
    CarData
ON
    #summary.id = CarData.id AND (CarData.TimeSent BETWEEN #summary.Start AND #summary.Stop)

答案 1 :(得分:0)

这里有一种方法,虽然我不喜欢它做3次子查询。这是我希望有人有更好主意的案例之一。

update #summary
  set TopSpeed = 
  (
      select top 1 TopSpeed
      from CarData
      where CarData.VehicleId = #summary.VehicleId 
      and CarData.TimeSent between #summary.Start and #summary.Stop
      order by CarData.TopSpeed desc, TimeSent desc
  ) 
  SpeedTime = 
  (
      select top 1 SpeedTime
      from CarData
      where CarData.VehicleId = #summary.VehicleId 
      and CarData.TimeSent between #summary.Start and #summary.Stop
      order by CarData.TopSpeed desc, TimeSent desc
  ) 
  SpeedDriver = 
  (
      select top 1 SpeedDriver
      from CarData
      where CarData.VehicleId = #summary.VehicleId 
      and CarData.TimeSent between #summary.Start and #summary.Stop
      order by CarData.TopSpeed desc, TimeSent desc
    )