PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Pilih dari SUM() dari beberapa kolom dan gabung di postgreSQL

Saya rasa Anda menginginkan FULL OUTER JOIN dari semua 5 kueri:

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



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Batasan kunci asing yang kompleks di SQLAlchemy

  2. Kueri PostgreSQL mengembalikan nilai yang tidak ada di database saya

  3. Sebelum dan Setelah memicu pada acara yang sama? Isi tabel anak PostgreSQL

  4. Bagaimana saya bisa mengembalikan '0' dari kueri di pgsql, jika barisnya tidak ada?

  5. Rails 3.2 - metode tidak terdefinisi `where' untuk #<Array:... - Query dari Model.where()