我想使用聚合函数更新设置列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);
函数。
答案 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
关于添加的其他几点说明:
i.dist
有很多零,那么删除where
子句中的零值理论上可以加快查询速度