1

Table 1 (~1000 rows): Column_names : date, time, location_name, sum_severity_of_incident

Table 2 (~1000,000 rows) Column_names: date, time, location_name, vehicle_name, number of people, severity_of_incident - (double precision type - between 0 & 1)

Table 2 contains list of incidents with severity. I am trying to fill the values in the sum_severity_of_incident column in table 1 by summing the values in the severity_of_incident column in Table 2 which have the same date, time & location_name.

I am new to Postgresql and this problem looks like a FOR loop problem in any other programming language. I could not find a straightforward solution in postgresql.

2 Answers 2

2

This is a simple update with group by:

update table1
    set num_of_incidents = t2.sums
    from (select date, time, location, sum(severity_of_incident) as sums
          from table2 
          group by date, time, location
         ) t2
    where t2.date = table1.date and t2.time = table1.time and t2.location = table1.location;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It worked perfectly. Just curious: Is this the fastest method? Can you think of any other way of doing this?
@Aman . . . This should work well. Under some circumstances, a correlated subquery might have better performance.
0

Below SQL will give you number of incidents per date, time, location_name. Insert the result into table1.

select date, time, location_name, count(*) as number_of_incidents from table2 group by date, time, location_name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.