[英]update count from a table in another
I am new to postgres so sry if this sound like a stupid question如果这听起来像一个愚蠢的问题,我是 postgres 的新手所以很抱歉
I have a polygons shp in postgresql named t1 with fields like this我在 postgresql 中有一个名为 t1 的多边形 shp,带有这样的字段
id | area | grid_id
1 | 10 | 01_01
2 | 100 | 01_02
3 | 1000 | 01_03
4 | 10 | 01_01
I want to count the poligons with a certain unique "grid_id" which I can make with我想用我可以制作的某个独特的“grid_id”来计算 poligons
SELECT COUNT (*) from public.t1 group by grid_id
Now I want to update another table, t2, in a field "nr_polig" with the number of polygons corresponding to each unique grid_id现在我想用与每个唯一 grid_id 对应的多边形数量更新字段“nr_polig”中的另一个表 t2
id | name | nr_polig
1 | 01_01 |
2 | 01_02 |
3 | 01_03 |
4 | 01_04 |
I ve tried我试过了
Update public.t2 set nr_polig = (
SELECT COUNT(*) from public.t1 group by grid_id where public.grid_id = grid_id
)
later_edit稍后_编辑
it worked like this它是这样工作的
UPDATE public.t2
set nr_polig = (SELECT COUNT (*) from public.t1 where public.t1.grid_id = public.t2.name)
You can join the tables:您可以加入表:
UPDATE public.t2
SET nr_polig = s.cnt
FROM (SELECT grid_id, count(*) AS cnt
FROM public.t1
GROUP BY grid_id) AS s
WHERE s.grid_id = t2.grid_id;
You need to properly correlate the subquery by prefixing column name with the table it belongs to.您需要通过在列名前面加上它所属的表来正确关联子查询。 Also the
group by
clause is not needed in the subquery.此外,子查询中不需要
group by
子句。
update t2 set nr_polig = (
select count(*)
from t1
where t1.grid_id = t2.name
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.