如何通过比较SQL Server中的两个表数据来更新表

时间:2018-06-29 06:32:18

标签: sql tsql

表1:(主表)

ALERT_ID    WORK_FLOW_ID
21  NULL
22  NULL
23  NULL
24  NULL
25  NULL
26  NULL

表2:-

ID  ALERT_ID
1   0
2   1
3   1
4   2
5   2
6   3

表3:-

ID  PROGRAM_WORKFLOW_ID
1   21
2   22
3   23
4   24
5   25
6   26

我的输出:

ALERT_ID    WORK_FLOW_ID 
 21              Null
 22              21
 23              21
 24              22
 25              22
 26              23

2 个答案:

答案 0 :(得分:0)

这应该有效:

With cte as
(Select *, ROW_NUMBER() over (order by (Select null)) as ranking from #tbl1)
,cte2 as
(Select cte.Alert_Id, #tbl3.PROGRAM_WORKFLOW_ID from cte 
join #tbl2 on cte.ranking = #tbl2.ID
left join #tbl3 on #tbl3.ID = #tbl2.ALERT_ID)
Update #tbl1 
Set WORK_FLOW_ID = cte2.PROGRAM_WORKFLOW_ID
from #tbl1 join cte2
on #tbl1.ALERT_ID = cte2.Alert_Id

模式:

Create table #tbl1 (ALERT_ID int,    WORK_FLOW_ID int )
Insert into #tbl1 values (21,  NULL),(22,  NULL),(23 , NULL),(24  ,NULL),(25 , NULL),(26 , NULL)

Create table #tbl2 (ID int,  ALERT_ID int)
Insert into #tbl2 values (1 ,  0),(2,   1),(3 ,  1),(4  , 2),(5 ,  2),(6  , 3)

Create table #tbl3 (ID int,  PROGRAM_WORKFLOW_ID int)
Insert into #tbl3 values (1 ,  21),(2 ,  22),(3 ,  23),(4 ,  24),(5,  25),(6 ,  26)

答案 1 :(得分:0)

您需要执行SELF JOIN

select t1.ALERT_ID , t33.PROGRAM_WORKFLOW_ID
from table1 t1 inner join
     table3 t3 
     on t3.PROGRAM_WORKFLOW_ID = t1.ALERT_ID inner join
     table2 t2 on
     t2.id = t3.id left join
     table3 t33
     on t33.id = t2.ALERT_ID;