【问题标题】:Display total where row number is max row_number显示总计,其中行号为最大 row_number
【发布时间】:2021-08-12 06:20:01
【问题描述】:

我有一个显示发票信息的查询,并且在最后一列显示供应商的总余额,我只想在该供应商发票条目的最后一行显示总余额。

即。结果可能包含 20 个供应商的 100 张发票,每个供应商有不同数量的发票,Account_Total 应该只显示在该特定 pt_account 的最后一行。 (row_number 是该 pt_account 的 MAX 值。)

当我尝试时,我得到一个窗口错误。

select 
    row_number() over (order by pt_account, pt_trdate), 
    pt_account, pt_trdate, pt_supref, pt_trref, pt_trtype, 
    pt_trvalue - pt_vatval [Net], pt_vatval [Vat], PT_TRVALUE [Total], 
    pt_trbal [Balance],
    Account_Total = (select sum(pt.pt_trbal) from ptran pt 
                     where pt.pt_account = pt1.pt_account)
from 
    ptran pt1
where 
    pt_trbal <> 0
    and pt_advance <> 'Y'
    and pt_account like 'A%'

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql sql-server tsql window-functions


【解决方案1】:

您可以使用case 表达式。此外,不需要子查询。您可以使用窗口函数:

select row_number() over (order by pt_account, pt_trdate),
       pt_account, pt_trdate, pt_supref, pt_trref, pt_trtype, pt_trvalue-pt_vatval [Net], pt_vatval [Vat], PT_TRVALUE [Total], pt_trbal [Balance],
       (case when 1 = row_number() over (order by pt_account, pt_trdate desc)
             then sum(pt.pt_trval) over (partition by pt_account)
        end) as Account_Total
from ptran pt1
where pt_trbal <> 0 and pt_advance <> 'Y' and pt_account like 'A%'
order by pt.account, pt_trdate;

【讨论】:

  • 这仅返回第一行的总数,它需要为每个 pt_account 的最终条目提供一个总数
  • @AlanMackintosh 。 . .哦,那应该是降序而不是升序。
猜你喜欢
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 2013-01-18
  • 2015-06-25
  • 2015-06-14
  • 1970-01-01
  • 2017-03-31
  • 2018-06-30
相关资源
最近更新 更多