问题描述
我正在尝试对所有发票明细行求和,并使用CTE返回总金额的1行。但是,下面的CTE只是返回发票行之一。我究竟做错了什么?谢谢。
with getinvoices as
(
select
i.invoice_nbr,i.invoice_type_id,i.invoice_type_desc,i.invoice_total_amount,row_number() over (partition by i.invoice_nbr order by i.rowid) rn,sum(i.line_amount) as "Sum Of Line Amount"
from
ods_dev.invoices i
where
i.invoice_date >= '7/1/2020'
and i.invoice_date < '7/2/2020'
and i.invoice_nbr is not null
group by
i.invoice_nbr,i.rowid
)
select *
from getinvoices g
where g.rn = 1
order by g.invoice_nbr
解决方法
我猜您只是想要一个聚合查询:
SELECT i.invoice_nbr,i.invoice_type_id,i.invoice_type_desc,i.invoice_total_amount,SUM(i.line_amount) as "Sum Of Line Amount"
FROM ods_dev.invoices i
WHERE i.invoice_date >= '2020-07-01' and i.invoice_date < '2020-07-02' and
i.invoice_nbr IS NOT NULL
GROUP BY i.invoice_nbr,i.invoice_total_amount