如何使用groupby对特定列求和,以及如何不使用groupby对特定列求和?

23c0lvtd  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(373)

我这里有一个示例表,列是 transaction_id , total_amount , collected_amount .
交易记录合计收款金额110060110040240301035042020
用于快速访问的表\u图像\u
我只想得到一个结果来得到总金额的总和,但是有一个事务id为的group by。还有收集的金额的总和(没有group by,只需要使用sql sum函数)
这是预期的输出。
合计收款金额210210
期望\u输出\u快速\u访问
如您所见,在total\u amount列中,它类似于

SUM(total_amount) from sample_table GROUP BY transaction_id

当在预期输出上的收集数量中时,查询如下

SUM(collected_amount) from sample_table

谢谢您!

mspsb9vt

mspsb9vt1#

我建议聚合两次:

select sum(total_amount), sum(collected_amount)
from (select transaction_id, total_amount, sum(collected_amount) as collected_amount
      from t
      group by transaction_id, total_amount
     ) tt;
whlutmcx

whlutmcx2#

对收集的数量求和将提供一个标量结果。分组和求和将在结果中提供n个记录,其中n等于唯一的事务ID。因此,不能将这两个查询组合成一个查询。但是,您可以运行嵌套查询,我通常避免这样做,因为这样做可能会降低效率。

select
    transaction_id,
    sum(total_amount),
    (select sum(collected_amount) from sample_table)
from sample_table
group by transaction_id;

另一种选择是尝试 OVER mysql中的语句。

select
    transaction_id,
    sum(total_amount) over(partition by transaction_id) total_amount,
    sum(collected_amount) over() collected_amount
from sample_table;

相关问题