PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Seleziona da SUM() di più colonne e unisciti a postgreSQL

Penso che tu voglia un'UNIONE ESTERNA COMPLETA di tutte e 5 le query:

with
  cte1 as (
    select id, sum(num1) val1 from details   
    group by id
    order by sum(num1) desc nulls last limit 10
  ),
  cte2 as (
    select id, sum(num2) val2 from details   
    group by id
    order by sum(num2) desc nulls last limit 10
  ),  
  cte3 as (
    select id, sum(num3) val3 from details   
    group by id
    order by sum(num3) desc nulls last limit 10
  ),  
  cte4 as (
    select id, sum(num4) val4 from details   
    group by id
    order by sum(num4) desc nulls last limit 10
  ),  
  cte5 as (
    select id, sum(num5) val5 from details   
    group by id
    order by sum(num5) desc nulls last limit 10
  )
select coalesce(c1.id, c2.id, c3.id, c4.id, c5.id) id,
       c1.val1, c2.val2, c3.val3, c4.val4, c5.val5
from cte1 c1
full outer join cte2 c2 on c2.id = c1.id
full outer join cte3 c3 on c3.id = c2.id
full outer join cte4 c4 on c4.id = c3.id
full outer join cte5 c5 on c5.id = c4.id