作为Postgresql查询结果最后一条记录的行的总和
我的表列是这样的,我想要最后一行中所有记录的总和,而不使用UNION作为Postgresql查询结果最后一条记录的行的总和,sql,postgresql,Sql,Postgresql,我的表列是这样的,我想要最后一行中所有记录的总和,而不使用UNION no_of_books 1 3 3 3 5 预期结果将是 no_of_books 1 3 3 3 5 15 我试过这样做,但在PostgreSQL中寻找更好的功能,比如Oracle select aa.no_of_books sum_prod from (SELECT prodcount FROM "table1") aa union all select sum(bb.su
no_of_books
1
3
3
3
5
预期结果将是
no_of_books
1
3
3
3
5
15
我试过这样做,但在PostgreSQL中寻找更好的功能,比如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
或
您可以对子查询使用
rollup
:
select coalesce(no_of_books, (select sum(no_of_books) from table t))
from table t
group by rollup(no_of_books);
但是,这可以通过sum()
直接完成:
select sum(no_of_books)
from table t
group by rollup(no_of_books);
使用
汇总
:
select sum(no_of_books)
from books t
group by rollup(no_of_books)
或cube
select sum(no_of_books)
from books t
group by cube(no_of_books);
select sum(no_of_books)
from books t
group by cube(no_of_books);