【问题标题】:How do I make calculation from 2 columns in one table, into new table? Postgresql如何从一张表中的 2 列计算到新表中? PostgreSQL
【发布时间】:2026-01-22 14:00:01
【问题描述】:

我有一张名为“postgres”的大表,它有 3 列(日期、打开、关闭)和 65000 行。

 postgres
    
        Date       |      Open       |       Close
----------------------------------------------------------
        2019-01-01 |     1.03212     |     1.03243
        2019-01-01 |     1.06212     |     1.09243
        2019-01-02 |     1.02212     |     1.08243
        2019-01-04 |     1.08212     |     1.07243
        +65000 rows

我需要计算一下。类似(case when Open < Close then 1 else 0 end) 到表中的所有行,接下来我需要将答案放入新表“Zad2”中。它需要看起来:

    Zad2
    
    Type       |     Amount  
-------------------------------  
    positive   |     23232     
    negative   |     11433     
    equal      |     322        

谢谢帮助,对不起我的英语)

【问题讨论】:

    标签: sql postgresql create-table calculation case-when


    【解决方案1】:

    您可以使用case 表达式:

    select (case when open < close  then 'increasing'
                 when open > close  then 'decreasing'
                 when open = close  then 'equal'
            end) as grp, count(*)
    from t
    group by grp;
    

    我不确定“积极”和“消极”应该是什么意思,所以我贴上了对我有意义的标签。

    您可以使用insert(如果该表已存在)或create table as(如果该表不存在)将结果放入一个新表中。

    【讨论】:

    • 非常感谢!我非常接近解决方案,我尴尬了几天))谢谢!!!!
    最近更新 更多