可以使用最终结果集显示内部查询的结果集

时间:2018-01-31 11:34:02

标签: sql postgresql inner-query

我有一个包含一些数据的表

====================
Record  | Record_Count
1       |   12
3       |   87
5       |   43
6       |   54
1       |   43
3       |   32
5       |   65
6       |   43

我有一个查询返回按记录

分组的记录计数总和
select record,sum(record_count)
FROM table_name
WHERE <conditions>
GROUP BY tcpa_code
ORDER BY sum(record_count)

结果是这样的

====================
Record  | Record_Count
1       |   55
3       |   119
5       |   108
6       |   97

现在我还想要一个总计record_count(所有记录数的总和)。

事情是我也想要上面的结果集和总计。

我试过这个

select sum(subquery.record_count)
from (
select record,sum(record_count)
FROM table_name
WHERE <conditions>
GROUP BY tcpa_code
ORDER BY sum(record_count) ) as subquery

但是通过使用这个,我将丢失个人record_count总和。

所以我的问题是,我是否可以在单个查询中实现包含每条记录的record_count总和和record_count总计的结果集?

3 个答案:

答案 0 :(得分:0)

您可以使用next.data.client = data; 来实现您的需求:

union

点击此处 - SQL Fiddle

如果您的数据库支持(select cast(record as varchar(16)) record,sum(record_count) from schema.table group by 1) union (select 'Grand_Total' as record,sum(record_count) from schema.table group by 1); ,您也可以使用:

group by ... with rollup

点击此处 - SQL Fiddle

答案 1 :(得分:0)

要保存一些输入,可以使用公用表表达式(cte):

with cte as
(
    select record, sum(record_count) rsum
    FROM table_name
    WHERE <conditions>
    GROUP BY record
)
select record, rsum from cte
union all
select 'Grand_Total', sum(rsum) from cte

答案 2 :(得分:0)

你应该使用PostgrSQL的windows functions

至于此查询,

SELECT record, record_count, sum(record_count) OVER()
    FROM (
         SELECT record, sum(record_count) record_count
           FROM table_name
           WHERE <conditions>
           GROUP BY tcpa_code
           ORDER BY sum(record_count) 
          ) as subquery