我有来自此查询的数据:
with countedresult As
(
select ROW_NUMBER() over(partition by d_hotbox order by d.D_hotbox,d.start_date) as ADS,d.ID,
d.D_hotbox,
d.D_PWM_location,
d.start_date,
d.Last_date--,
h.SERIAL_NUMBER
from D_FLEET d
)
select countedresult.ID,
countedresult.D_HOTBOX,
countedresult.D_PWM_location,
countedresult.start_date,
countedresult.Last_date,
LAG(ID, 1) over (partition by d_hotbox order by d_hotbox, start_date) as previous_id,
ads HB_Run_Number
from countedresult
order by d_hotbox, HB_Run_Number DESC
我必须只更新表中的两列,它们是PREVIOUS_ID,RUN_NO。
我想在另一个表中插入这些值
[dbo].[D_FLEET]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[D__LOCATION] [int] NOT NULL,
[D_BOX] [int] NULL,
[D__MODULE] [int] NULL,
[ST_DATE] [date] NULL,
[LT_DATE] [date] NULL,
[S_START_DATE] [date] NULL,
[S_LAST_DATE] [date] NULL,
[LT_DATE_@1A] [date] NULL,
[C_LAST_SS] [float] NULL,
[S_AVG] [float] NULL,
[SP_MIN] [float] NULL,
[SP_MAX] [float] NULL,
[H_TYPE] [nvarchar](50) NULL,
[R_FRU] [nvarchar](50) NULL,
[NILD] [nvarchar](50) NULL,
[RLACE] [nvarchar](50) NULL,
[HRADE] [float] NULL,
[HTUS] [nvarchar](50) NULL,
[HDULE] [nvarchar](50) NULL,
[HT_DATE] [date] NULL,
[OAG] [nvarchar](50) NULL,
[ID_DATE] [datetime] NULL,
[UPDATED_DATE] [datetime] NULL,
[Run_Type] [nvarchar](50) NULL,
[RUN_NO] [nvarchar](50) NULL,
[PREVIOUS_ID] [int] NULL
)
我想更新以下值:
这是正确的方法吗?
我无法理解如何执行此操作,因为我正在执行从查询到表的更新。
感谢任何帮助。
答案 0 :(得分:1)
您需要将结果加入目标表并更新,如下所示。
请注意JOIN
(标准中存在错误)以及我们如何在UPDATE
中使用别名。
with countedresult As
(
select ROW_NUMBER() over(partition by d_hotbox order by d.D_hotbox,d.start_date) as ADS,d.ID,
d.D_hotbox,
d.D_PWM_location,
d.start_date,
d.Last_date--,
h.SERIAL_NUMBER
from D_FLEET d
)
UPDATE T
SET
RUN_NO = LAG(ID, 1) over (partition by d_hotbox order by d_hotbox, start_date)
PREVIOUS_ID = ads
from countedresult
join D_FLEET AS T ON T.ID = countedresult.ID
order by d_hotbox, HB_Run_Number DESC
答案 1 :(得分:1)
with countedresult As
( select ROW_NUMBER() over (partition by d_hotbox order by start_date) as ADS
, LAG(ID, 1) over (partition by d_hotbox order by start_date) as previous_id
, ID
from D_FLEET
)
update D_FLEET
set HB_RUN_NUMBER = countedresult.ADS
, PREVIOUS_ID = countedresult.PREVIOUS_ID
from D_FLEET
join countedresult
on D_FLEET.ID = countedresult.ID