简体   繁体   中英

update count from a table in another

I am new to postgres so sry if this sound like a stupid question

I have a polygons shp in postgresql named t1 with fields like this

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

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

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
)

but its updating the total number of polygons

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.

update t2 set nr_polig = (
    select count(*)  
    from t1
    where t1.grid_id = t2.name
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM