Search code examples
sqlpostgresqlcreate-tablecalculationcase-when

How do I make calculation from 2 columns in one table, into new table? Postgresql


I have one big table called "postgres" it has 3 columns(Date,Open,Close) and 65000 rows.

 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

I need to make calculation. Something like that (case when Open < Close then 1 else 0 end) to all rows in table, and next I need to put the answers into new table "Zad2". It need to look look that:

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

Thx for help, and sorry for my English)


Solution

  • You can use a case expression:

    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;
    

    I'm not sure what "positive" and "negative" are supposed to mean, so I put in labels that make sense to me.

    You can put the results in a new table using either insert (if the table already exists) or create table as (if the table does not exist).