从select中更新具有更多列的多个列

时间:2018-04-16 12:06:20

标签: sql oracle

我需要更新给定查询中的2列,但问题是查询有2列以上,所以如果我取消其他列,这是正确的语法:

UPDATE myTable TAO 
  SET (TAO.BASE_AMT,TAO.TAX_CD_VAT_PCT) = ( 
 SELECT SUM(decode(TAX_CD_VAT_PCT 
 , 0 
 , 0 
 ,d.monetary_amount)) 
 , MAX (D.TAX_CD_VAT_PCT) 
  FROM ps_VCHR_LINE_WTHD w 
  , PS_DISTRIB_LINE d 
 WHERE 1=1 
 -- some conditions
  GROUP BY d.business_unit, d.voucher_id 
  ORDER BY 1, 2)

原始查询就是这样:

 SELECT d.business_unit, d.voucher_id,SUM(decode(TAX_CD_VAT_PCT 
 , 0 
 , 0 
 ,d.monetary_amount)) 
 , MAX (D.TAX_CD_VAT_PCT) 
  FROM ps_VCHR_LINE_WTHD w 
  , PS_DISTRIB_LINE d 
 WHERE 1=1 
 -- some conditions
  GROUP BY d.business_unit, d.voucher_id 
  ORDER BY 1, 2)

因此,如果我删除d.business_unit, d.voucher_id,我会得到相同的结果吗?因为我在SQL开发人员中尝试了这个,当我删除它时,我没有得到相同的顶行。

有人可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:0)

使用MERGE声明。很难确定如何将更新语句与嵌套选择相关联(它似乎没有任何相关性)但是,假设它位于business_unitvoucher_id列上类似的东西:

MERGE INTO my_table dst
USING (
  SELECT d.business_unit,
         d.voucher_id,
         SUM( DECODE( TAX_CD_VAT_PCT, 0, 0, d.monetary_amount ) ) AS total_tax_cd_vat_pct,
         MAX (D.TAX_CD_VAT_PCT) AS max_tax_cd_vat_pct
  FROM   ps_VCHR_LINE_WTHD w 
         INNER JOIN
         PS_DISTRIB_LINE d 
         ON ( /* some conditions here */ )
  WHERE  1=1
         -- some conditions
  GROUP BY
         d.business_unit,
         d.voucher_id
) src
ON (
      src.business_unit = dst.business_unit
  AND src.voucher_id    = dst.voucher_id
)
WHEN MATCHED THEN
  UPDATE SET
   BASE_AMT       = src.total_tax_cd_vat_pct
   TAX_CD_VAT_PCT = src.max_tax_cd_vat_pct;