简体   繁体   中英

Getting value from MAX(Date) Row in SQL Server

I am trying to get the last supplier of an item, by using the MAX function. What I am trying to achieve is showing what the supplier name was for the row with the MAX(Date) for all the stock items (shown below as account links).

The code I am using bring up multiple dates for the same accountlink, and I am struggling to see why. My code is:

SELECT 
  MAX(TxDate) AS Date,
  ST.AccountLink,
  V.Account AS Supplier 

FROM _bvSTTransactionsFull AS ST 
  JOIN Vendor V on ST.DrCrAccount = V.DCLink

WHERE Module = 'AP' 
AND Id = 'OGrv'
GROUP BY ST.AccountLink, V.Account
ORDER BY AccountLink

But my results look like the below

在此处输入图像描述

Try this out

select AccountLink,Supplier,date from(SELECT 
ST.AccountLink,
V.Account AS Supplier,
TxDate as [date],
row_number()over(partition by ST.AccountLink order by TxDate desc)rownum

FROM _bvSTTransactionsFull AS ST 
  JOIN Vendor V on ST.DrCrAccount = V.DCLink

WHERE Module = 'AP' 
AND Id = 'OGrv')t
where t.rownum = 1

The group by has been removed and ranking function is used to achieve the output

You need a simple subquery to select the last supplier.

    select X.supplier as LastSupplier, X.Date as lastDate,  X.AccountLink
    from _bvSTTransactionsFull X 
    where X.Date = (select max(date) 
                    from _bvSTTransactionsFull Y 
                    where Y.AccountLink=X.AccountLink)

The subquery extracts the last date for any accountLink, so you can use it on the outer where condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM