如何将表的所有列值相加并使用Postgresql显示新行中的总数

时间:2017-01-04 06:22:56

标签: sql postgresql postgresql-9.3 postgresql-9.4

我使用普通的选择查询来显示所有行

SELECT 
    type,
    debit,
    credit,
    (debit-credit) as balance
from bank_cash_registers

显示如下图所示 enter image description here

现在我需要在Postgresql查询的帮助下将此总数显示为附加行,如下图所示。我怎样才能做到这一点?

enter image description here

并且还有基于类型的单独总计的任何选项,如下所示。 enter image description here

2 个答案:

答案 0 :(得分:3)

另一种方法是使用grouping sets。它的优点是它可以很容易地扩展。此外,我认为它是专门为此目的而创建的。

这应该比UNION解决方案更有效,因为数据只传递一次。

以下查询返回您想要的内容:

SELECT COALESCE(type, 'Total: '), SUM(debit), SUM(credit), SUM(debit - credit) AS balance
FROM bank_cash_registers
GROUP BY GROUPING SETS ((type, debit, credit), ());

以下查询将具有相同类型的值组合在一起(请注意,唯一更改的是GROUPING SETS子句):

SELECT COALESCE(type, 'Total: '), SUM(debit), SUM(credit), SUM(debit - credit) AS balance
FROM bank_cash_registers
GROUP BY GROUPING SETS ((type), ());

结果:

bank    0    1500    -1500
cash    0     700     -700
Total:  0    2200    -2200

您的更新问题可以通过以下方式解决:

SELECT
  CASE WHEN GROUPING(debit) > 0 THEN 'Total: ' ELSE type END AS type,
  SUM(debit), SUM(credit), SUM(debit - credit) AS balance
FROM bank_cash_registers
GROUP BY GROUPING SETS ((type, debit, credit), (type));

你甚至可以用

添加总数
(...) GROUPING SETS ((type, debit, credit), (type), ());

答案 1 :(得分:2)

SELECT type
    ,debit
    ,credit
    ,(debit - credit) as balance
FROM bank_cash_register

UNION ALL

SELECT 'Total: '
    ,sum(debit)
    ,sum(credit)
    ,sum((debit - credit))
FROM bank_cash_register

根据类型列

对总计进行分组
SELECT *
FROM (
    SELECT type
          ,debit
          ,credit
          ,(debit - credit) as balance
    FROM bank_cash_register

    UNION ALL

    SELECT type || '_total'
          ,sum(debit)
          ,sum(credit)
          ,sum((debit - credit))
    FROM bank_cash_register
    GROUP BY 1
    ) t
ORDER BY split_part(type, '_', 1)

浏览split_part()

Demo