PostgreSQL:使用聚合函数更新

时间:2016-02-14 15:52:17

标签: sql postgresql aggregate-functions

我想使用聚合函数更新设置列ibase的表UPDATE paneldata p SET ibase=SUM(1/i.dist) FROM ibaselang i WHERE p.gid=i.gid AND i.instp<p.period

ERROR:  aggregate functions are not allowed in UPDATE

这导致CREATE TABLE public.ibaselang ( gid integer, dist double precision, buildid integer, instp smallint ) WITH ( OIDS=FALSE );

表定义

WHERE

解决方案方法

不幸的是,我不知道如何在子查询中实现我的//My controller $genres = Genre::all(); $tracks = Track::all(); $beats = Beat::where('TrackVariantID', 1)->get(); return view('play.forfun.songselect')->with('genres', $genres)->with('tracks', $tracks)->with('beats', $beats); 函数。

3 个答案:

答案 0 :(得分:5)

这是一个通用的示例。

UPDATE public.customer_value cv
SET total_value = sub_q.sum_val 
FROM 
    (
    SELECT SUM(order_amount) AS sum_val, o.customer_id 
    FROM public.orders AS o
    GROUP BY o.customer_id
    ) AS sub_q
WHERE sub_q.customer_id = cv.customer_id;

如果您想全面尝试该示例,则可以创建如下的伪数据:

CREATE TABLE public.customer_value
(
  customer_id int 
, total_value numeric (10,2)
);

CREATE TABLE public.orders 
(
  customer_id int
, order_amount numeric(10,2)
);

INSERT INTO public.customer_value
(customer_id)
VALUES 
  (1)
, (2);


INSERT INTO public.orders
(customer_id, order_amount)
VALUES 
 (1, 10)
,(1, 10)
,(2, 7.5)
,(2, 7.5);

答案 1 :(得分:4)

尝试使用这样的相关查询:

UPDATE paneldata p
SET p.ibase=(select SUM(1/i.dist)
             FROM ibaselang i
             WHERE p.gid=i.gid
             AND i.instp<p.period)

答案 2 :(得分:4)

我不知道这是多么有效,但它应该有效:

with updates as (
  select
    p.gid, sum (i.dist) as dist
  from
    paneldata p
    join ibaselang i on
      p.id = i.gid and
      i.instp < p.period
  where
    i.dist != 0
  group by
    p.gid
)
update paneldata p
set
  ibase = 1 / u.dist
from
  updates u
where
  p.gid = u.pid and
  u.dist != 0

关于添加的其他几点说明:

  1. 如果您的i.dist有很多零,那么删除where子句中的零值理论上可以加快查询速度
  2. 您可能存在除以零错误的潜在漏洞 - 这也在update语句中处理。也许你的数据没有这个条件,但最好还是处理它以确保