Sum of rows as the last record from Postgresql query result

Sum of rows as the last record from Postgresql query result



My Table column is like this, I want the sum of all records in the last row without using UNION


no_of_books
1
3
3
3
5



Expected result would be


no_of_books
1
3
3
3
5
15



I have tried like this, but looking for better fuctions in PostgreSQL like Oracle


select aa.no_of_books sum_prod from (SELECT prodcount
FROM "table1") aa
union all
select sum(bb.sum_prod) from (
select aa.no_of_books sum_prod from (SELECT prodcount
FROM "table1") aa ) bb



OR


select no_of_books
from table t
union all
select sum(no_of_books)
from table t ;




2 Answers
2



You can use rollup with subquery :


rollup


select coalesce(no_of_books, (select sum(no_of_books) from table t))
from table t
group by rollup(no_of_books);



However, this would be done with sum() directly :


sum()


select sum(no_of_books)
from table t
group by rollup(no_of_books);



Use rollup :


rollup


select sum(no_of_books)
from books t
group by rollup(no_of_books)



or cube


cube


select sum(no_of_books)
from books t
group by cube(no_of_books);



(SQL Fiddle Demo)


SQL Fiddle Demo



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

Node.js puppeteer - Use values from array in a loop to cycle through pages