使用“选择查询"更新表带有 where 子句

2022-01-17 00:00:00 join sql-update sql select sql-server

我想实现以下目标:

表(my_table)的当前状态

 id        totalX          totalY          totalZ               
 --------- --------------  --------------  --------------       
         9             34              334             0      
        10              6               56             0      
        11             21              251             0      
        12              3               93             0   

(my_table2)的查询结果

select id,count(*) as total FROM my_table2 WHERE column_2 = 1 GROUP BY id

 id        total               
 --------- --------------       
         9            500      
        10            600      
        11            700      
        12            800  

表 (my_table) 的预期状态

 id        totalX          totalY          totalZ               
 --------- --------------  --------------  --------------       
         9             34              334             500      
        10              6               56             600      
        11             21              251             700      
        12              3               93             800    

这可以在一个更新查询中完成吗?我正在寻找 RHEL 5.0 上的 Sybase ASE 12.5

Can this be done in ONE update query ? I am looking for Sybase ASE 12.5 on a RHEL 5.0

我找不到 Sybase 的解决方案,但该问题的当前答案适用于 MS SQL Server..

I coudn't find the solution for Sybase, but the current answer to the question works on MS SQL Server..

推荐答案

   update 
          my_table 
   set 
      my_table.totalZ = t.total 
   FROM
    my_table mt
    INNER JOIN 
       (select id,count(*) as total 
       FROM my_table2 
      WHERE column_2 = 1 GROUP BY id) t
   on mt.id  = t.id

更新 在 MS SQL Server 中,这就是你要做的.OP 指出这在 Sybase 中不起作用.

UPDATE In MS SQL Server this is what you would do. The OP noted this doesn't work in Sybase.

相关文章