How to use a SQL window function to calculate a percentage of an aggregate

后端 未结 2 1420
情歌与酒
情歌与酒 2021-02-01 08:17

I need to calculate percentages of various dimensions in a table. I\'d like to simplify things by using window functions to calculate the denominator, however I am having an iss

2条回答
  •  轮回少年
    2021-02-01 08:37

    Do you need to do it all with window functions? Sounds like you just need to group the result you have by d1 and d2 and then sum the sums:

    select d1, d2, sum(p)
    from (
        select d1, d2, v/sum(v) over (partition by d1) as p
        from test
    ) as dt
    group by d1, d2
    

    That gives me this:

     d1 | d2 |          sum           
    ----+----+------------------------
     a  | x  | 0.25000000000000000000
     a  | y  | 0.75000000000000000000
     b  | x  | 1.00000000000000000000
    

提交回复
热议问题