【问题标题】:Postgres insert all rows with max min valuesPostgres 插入所有具有最大最小值的行
【发布时间】:2015-11-03 14:58:49
【问题描述】:

我想从一个表中选择所有行并将它们插入到另一个表中,所有行上只有最大值和最小值。无法弄清楚如何在没有 group by 子句的情况下编写此内容。它是一个大表,所以 (update set=? from (select max...)) 会变慢

表1:

id,values  
1,2  
2,4  
3,1  

表2:

id,max,min  
1,4,1  
2,4,1  
3,4,1  

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    这里再次尝试使用 窗口函数 (SQLFiddle: http://sqlfiddle.com/#!15/2978e) 这是获取数据的选择。

    select 
      id, 
      min(values) over () as min, 
      max(values) over () as max 
    from Table1
    

    插入这些值,必须执行此 sql

    insert into table2 (id, min, max)
    select 
      id, 
      min(values) over () as min, 
      max(values) over () as max 
    from Table1
    

    或从sql 创建 table2

    create table table2 as
    select 
      id, 
      min(values) over () as min, 
      max(values) over () as max 
    from Table1
    

    【讨论】:

      【解决方案2】:

      这样就可以了:

      SELECT n1.id,
             n2.mymax,
             n2.mymin
      FROM
        (SELECT MIN(values) AS mymin,
                MAX(values) AS mymax
         FROM dbTable) n2,
           dbTable n1;
      

      SQL 小提琴here:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 1970-01-01
        • 2021-01-03
        相关资源
        最近更新 更多