如何使用Postgresql对表中所有列的值求和并在新行中显示总计

如何使用Postgresql对表中所有列的值求和并在新行中显示总计,sql,postgresql,postgresql-9.3,postgresql-9.4,Sql,Postgresql,Postgresql 9.3,Postgresql 9.4,我正在使用普通选择查询来显示所有行 SELECT type, debit, credit, (debit-credit) as balance from bank_cash_registers 其显示如下图所示 现在我需要在Postgresql查询的帮助下,将这个总数显示为一个额外的行,如下图所示。我怎样才能做到这一点 此外,是否有基于以下类型的单独总计选项。。 根据“类型”列对总计进行分组的步骤 SELECT * FROM ( SELECT

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

SELECT 
    type,
    debit,
    credit,
    (debit-credit) as balance
from bank_cash_registers
其显示如下图所示

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

此外,是否有基于以下类型的单独总计选项。。


根据“类型”列对总计进行分组的步骤

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)
通过


根据“类型”列对总计进行分组的步骤

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)
通过


另一种方法是使用。它的优点是易于扩展。此外,我认为它是专门为此目的而创建的

这应该比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子句):

结果:

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), ());

另一种方法是使用。它的优点是易于扩展。此外,我认为它是专门为此目的而创建的

这应该比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子句):

结果:

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), ());

是否可以根据类型显示多个总计?我在问题中更新了。是否可以根据类型显示多个总计?我更新了这个问题。