使用select语句更新列

时间:2017-05-15 15:00:32

标签: sql select firebird

我想根据您在下面找到我的查询的select语句的结果更新列,我的代码无法正常工作: 我在所有列上都获得了相同的数据

update ACHATS  b set 
QUANTITE=(select sum(QUANTITE)     from ACHAT_DETAILS a where a.NUMERO_D_ACHAT=(SELECT max(ID_ACHAT) M_ID_ACHAT from ACHATS) 
group by a.NUMERO_D_ACHAT) ,
PRIX_HT=(select sum(PRIX_HT)       from ACHAT_DETAILS a where a.NUMERO_D_ACHAT=(SELECT max(ID_ACHAT) M_ID_ACHAT from ACHATS) 
group by a.NUMERO_D_ACHAT),
PRIX_TTC=(select sum(PRIX_HT) from ACHAT_DETAILS a where a.NUMERO_D_ACHAT=(SELECT max(ID_ACHAT) M_ID_ACHAT from ACHATS) 
group by a.NUMERO_D_ACHAT);

2 个答案:

答案 0 :(得分:0)

所以要测试一下,请尝试下面的代码,看看这是否是您期望用来更新表格的结果:

   WITH B AS (
    SELECT  MAX(M_ID_ACHAT) AS NUMERO_D_ACHAT
          , SUM(QUANTITE) AS QUANTITE
          , SUM(PRIX_HT) AS PRIX_HT
          , SUM(PRIX_TTC) AS PRIX_TTC
    FROM    ACHAT_DETAILS
    GROUP BY 
        MAX(M_ID_ACHAT)
    )


SELECT
    b.QUANTITE
    ,b.PRIX_HT
    ,b.PRIX_TTC
FROM ACHAT_DETAILS a
JOIN  b
    ON a.NUMERO_D_ACHAT = b.NUMERO_D_ACHAT

接下来,如果一切看起来都不错,那么你可以运行它(我想我的语法正确):

WITH A AS (
SELECT  MAX(M_ID_ACHAT) AS NUMERO_D_ACHAT
      , SUM(QUANTITE) AS QUANTITE
      , SUM(PRIX_HT) AS PRIX_HT
      , SUM(PRIX_TTC) AS PRIX_TTC
FROM    ACHAT_DETAILS
GROUP BY 
    MAX(M_ID_ACHAT)
)


MERGE INTO ACHATS AS u
    USING A
    ON u.NUMERO_D_ACHAT = a.NUMERO_D_ACHAT
    WHEN MATCHED THEN
        UPDATE 
            SET 
             u.QUANTITE = a.QUANTITE
            ,u.PRIX_HT = a.PRIX_HT
            ,u.PRIX_TTC = a.PRIX_TTC

答案 1 :(得分:0)

问题的正确更新查询是:

update ACHATS b set 
  QUANTITE = (select sum(QUANTITE)
                from ACHAT_DETAILS a 
                where a.NUMERO_D_ACHAT = (
                  select max(ID_ACHAT)
                    from ACHATS)
             ),
  PRIX_HT = (select sum(PRIX_HT)
               from ACHAT_DETAILS a 
               where a.NUMERO_D_ACHAT = (
                 select max(ID_ACHAT)  
                   from ACHATS)
            ),
  PRIX_TTC = (select sum(PRIX_HT)  
                from ACHAT_DETAILS a 
                where a.NUMERO_D_ACHAT = (
                  select max(ID_ACHAT)
                  from ACHATS)
             )
  where b.ID_ACHAT = (select max(ID_ACHAT)
                        from ACHATS)