Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

amazon redshift - How to multiple decimal numbers in column within a group by?

I have sql table that looks like this:

date                  id       value     type
2020-01-01            1        1.03      a
2020-01-01            1        1.02      a
2020-01-02            2        1.06      a
2020-01-02            2        1.2       a
2020-01-03            3        1.09      b

I need to build a query that groups by date,id, and type by multiplying the value column whereever type = 'a'.

what new table should look like:

date                  id       value      type
2020-01-01            1        1.0506      a
2020-01-02            2        1.272       a
2020-01-03            3        1.09        b

currently I am building this query,

select 
date, id, value, type
from my_table
where date between 'some date' and 'some date'

and trying to fit in EXP(SUM(LOG(value)

but, how do I do the multiplication only where type = 'a' in a group by?

edit:

  1. there are more than 2 values in the type column
  2. I am using redshift. Not postgresql.
question from:https://stackoverflow.com/questions/65602155/how-to-multiple-decimal-numbers-in-column-within-a-group-by

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
select date
     , id
     -- use the 'case' syntax to check if it is type 'a'
     , case when type = 'a' then EXP(SUM(LOG(value::float))) -- your multiply logic
            else max(value) -- use min or max to pick only one value
       end as value
  from my_table
 where date between 'some date' and 'some date'
 group
    by date, id, type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...