如何在SQL Server 2014中找到最大值?

如何在SQL Server 2014中找到最大值?,sql,sql-server,max,Sql,Sql Server,Max,我有一个名为StatementSummary的表 SELECT * FROM StatementSummary WHERE AccountID = 1234 结果 StatementId StatementDate AccountId AmountDue ------------------------------------------------- 100 2017-10-16 1234 600 99 2017-09-16 1234

我有一个名为StatementSummary的表

SELECT * 
FROM StatementSummary 
WHERE AccountID = 1234
结果

StatementId StatementDate   AccountId   AmountDue
-------------------------------------------------
100     2017-10-16  1234        600
99      2017-09-16  1234        500
98      2017-08-16  1234        400
我有另一个表,其中有一个帐户列表。我试图给出显示每个帐户最后一次
应付金额的结果

我的代码:

SELECT 
    AccountID,
    (SELECT MAX(StatementDate) 
     FROM StatementSummary 
     GROUP BY AccountID) LastStatementDate,
    AmountDue
FROM
    Accounts A
INNER JOIN 
    StatementSummary S ON A.AccountId = S.AccountId

基本上,我想在
行数和
左连接上显示每个
AccountId

派生表的最后一条语句的所有详细信息,以显示所有帐户,无论是否有语句

select * 
from
(select row_number() over (partition by accountid order by statementdate desc) rn,
   accountid, statementdate,amount
from statementtable
) l
left outer join accountstable a
 on l.accountid = a.accountid
 And l.rn = 1
这听起来像是我在T-SQL中的一份工作

 SELECT a.*, last_ss.*
 FROM Accounts A
 cross apply (
  select top 1 * 
  from StatementSummary S ON A.AccountId = S.AccountId 
  order by StatementDate desc
  ) last_ss
或者,您可以使用获取帐户的最后日期:

 ; with l as (
   select accountid, max(StatementDate) 
   from StatementSummary
   group by accountid
 )
 select ...
 from Accounts a
   inner join l on l.accountid = a.accountid
   inner join StatementSummary ss on ss.accountid = a.accountid 
                  and l.StatementDate = ss.StatementDate

在这种情况下,您可以使用SQL Server窗口功能

SELECT DISTINCT
        a.AccountId,
        FIRST_VALUE(s.StatementDate) OVER (PARTITION BY s.AccountId ORDER BY s.StatementDate DESC) As LastStatementDate,
        FIRST_VALUE(s.AmountDue) OVER (PARTITION BY s.AccountId ORDER BY s.StatementDate DESC) As LastAmountDue
        FROM Accounts a
        INNER JOIN StatementSummary s
            ON a.AccountId = s.AccountId
基本上,OVER子句在您的数据中创建partitions,在本例中,是通过帐号(这些分区就是窗口)创建的。然后,我们告诉SQL Server按语句日期降序对每个分区内的数据进行排序,这样最后一条语句将位于分区的顶部,然后使用FIRST_VALUE函数仅获取第一行

最后,由于您对两个表之间的每个account/statement组合执行此操作,因此需要使用DISTINCT来表示您只希望每个account的每一行有一个副本


使用SQLServer中的窗口函数可以做很多有用的事情。这篇文章很好地介绍了它们:

limit
是mysql…OP是SQLServer@maSTAShuFu是的,如果没有
desc
,应该是
top 1
,则不会获得最新的对账单日期
max(amount)
将返回每个accountid的最大金额,不是语句表中最新记录的数量。为了使其更具可读性,请将Windows子句转换为命名的。运行此代码时,我收到以下错误消息:“FIRST_VALUE”不是可识别的内置函数名。\uPehaps,这是一个Oracle独有的函数?@user1777929-据文档显示,自SQL Server 2012以来,第一个_值似乎一直存在。您是否在旧的兼容级别上运行?