【问题标题】:Updating row count column in a table by counting number of rows in another table通过计算另一个表中的行数来更新表中的行数列
【发布时间】:2017-12-01 03:18:53
【问题描述】:

表 1(约 1000 行):Column_names:日期、时间、location_name、sum_severity_of_incident

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

表 2 包含具有严重性的事件列表。我正在尝试通过对表 2 中具有相同日期、时间和 location_name 的 severity_of_incident 列中的值求和来填充表 1 中 sum_severity_of_incident 列中的值。

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

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

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

    【讨论】:

    • 谢谢。它工作得很好。只是好奇:这是最快的方法吗?你能想到其他方法吗?
    • @Aman 。 . .这应该运作良好。在某些情况下,相关子查询可能具有更好的性能。
    【解决方案2】:

    下面的 SQL 将为您提供每个日期、时间和 location_name 的事件数。将结果插入table1。

    选择日期、时间、位置名称、计数(*)作为 number_of_incidents 从表 2 按日期、时间、位置名称分组;

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2021-07-22
      • 2015-03-02
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多