SQL 最后 100 条记录的平均值

问题描述 投票:0回答:1

在下面提供的查询中,我尝试用其相关平均值更新所有产品的估计价格字段:该产品在库存中最新 100 条记录的平均价格,其中实体类型为“报价”。

我编写了这个脚本,但遇到了错误“‘where 子句’中的未知列‘vtiger_products.productid’”

update `vtiger_products` set `vtiger_products`.`estimated_price` =
    (select avg(`subquery`.`unit_price`)
     from
         (select vtiger_inventoryproductrel.listprice as 'unit_price'
          from `vtiger_inventoryproductrel`
          left join `vtiger_crmentity` on `vtiger_inventoryproductrel`.`id` = `vtiger_crmentity`.`crmid`
          where `vtiger_crmentity`.`setype` = 'Quotes'
          and vtiger_inventoryproductrel.productid = vtiger_products.productid
          order by vtiger_crmentity.createdtime desc
          limit 100) as `subquery`
     )

如果有人帮助我找到解决方案,我会很高兴

sql mysql sql-update sql-order-by sql-limit
1个回答
0
投票

您可以为此使用联合更新。并将其与

ROW_NUMBER
结合起来,以获得每个
productid
的前 100 行。

此外,由于子查询现在不相关,因此您可以将它们放入 CTE 中以使其更具可读性。

with numbered as (
    select
      ipr.productid,
      ipr.listprice,
      ROW_NUMBER() OVER (PARTITION BY ipr.productid ORDER BY crm.createdtime DESC) as rn
    from vtiger_inventoryproductrel ipr
    join vtiger_crmentity crm on ipr.id = crm.crmid
    where crm.setype = 'Quotes'
),
averaged as (
    select
      n.productid,
      avg(n.listprice) as avg_price
    from numbered n
    group by
      n.productid
)
update
    vtiger_products p
    join averaged a on a.productid = p.productid and a.rn <= 100
set p.estimated_price = a.avg_price;
© www.soinside.com 2019 - 2024. All rights reserved.