小编典典

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

sql

我要实现以下目标:

表的当前状态(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

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


阅读 156

收藏
2021-04-19

共1个答案

小编典典

   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中不起作用。

2021-04-19