SQL CTE不返回总和

问题描述

我正在尝试对所有发票明细行求和,并使用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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...