通过计算另一个表中的行数来更新表中的行计数列

时间:2017-11-30 19:12:14

标签: sql postgresql

表1(~1000行):Column_names:date,time,location_name,sum_severity_of_incident

表2(~1000,000行)Column_names:日期,时间,location_name,vehicle_name,人数,severity_of_incident - (双精度类型 - 介于0和1之间)

表2包含严重性事件列表。我试图通过对表2中severity_of_incident列中的值进行求和来填充表1中sum_severity_of_incident列中的值,这些值具有相同的日期,时间和范围。 LOCATION_NAME。

我是Postgresql的新手,这个问题看起来像任何其他编程语言中的FOR循环问题。我在postgresql中找不到一个简单的解决方案。

2 个答案:

答案 0 :(得分:2)

这是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;

答案 1 :(得分:0)

SQL下面会给出每个日期,时间,location_name的事件数。将结果插入table1。

选择日期,时间,location_name,count(*)作为number_of_incidents 来自table2 按日期,时间,location_name;

分组