如何将一个表中的两列计算到新表中?postgresql语言

igsr9ssn  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(362)

我有一个名为“postgres”的大表,它有3列(date、open、close)和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

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

lmvvr0a8

lmvvr0a81#

你可以使用 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 (如果表不存在)。

相关问题