【问题标题】:SQL Server query for calculating sum用于计算总和的 SQL Server 查询
【发布时间】:2021-05-06 21:10:05
【问题描述】:

我正在尝试编写一个 SQL 查询来计算总和但没有成功。

假设我们有:

  • A 与列idtype
  • B,列ida_id(与表A相关)和amount

我成功计算了type 的记录数,如下例所示:

SELECT DISTINCT
    type,
    COUNT(A.id) OVER (PARTITION BY type) AS numOfRecords
FROM A;

如何计算每个type 的金额总和(将B 表中A 中所有不同类型的所有金额相加)?

【问题讨论】:

  • 如果你想总结一些东西,SUM 有什么问题?你为什么要使用DISTINCTOVER,而你真正想要的是GROUP BY 子句?

标签: sql sql-server


【解决方案1】:

您的查询通常会写成:

select type, count(*) as num_records
from A
group by type;

然后,您可以将b 合并为:

select a.type, count(*) as num_records, sum(b.amount)
from A left join
     (select a_id, sum(amount) as amount
      from b
      group by a_id
     ) b
     on b.a_id = a.id
group by a.type;

您也可以在没有子查询的情况下使用joinaggregate,但这会忽略计数。要解决这个问题,您可以使用count(distinct):

select a.type, count(distinct a.id) as num_records, sum(b.amount)
from A left join
     from b
     on b.a_id = a.id
group by a.type;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2012-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多