我试图写一个SQL查询计算总和没有成功。
假设我们有:
- 表
A
,列id
和type
- 表
B
,列id
,a_id
(与表A
的关系)和amount
我成功地通过type
计算记录数,如下例所示:
SELECT DISTINCT
type,
COUNT(A.id) OVER (PARTITION BY type) AS numOfRecords
FROM A;
如何计算每个type
的金额总和(对A
中所有不同类型的B
表中的所有金额求和)?
您的查询通常写成:
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;
您也可以不使用子查询join
和aggregate
,但这会导致计数错误。要解决这个问题,可以使用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;