Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
jimtimber
Yak Posting Veteran
60 Posts |
Posted - 2014-07-06 : 15:43:08
|
HI,I'm trying to bring through the most recent date from a field. A sample of what I am doing is:CustomerID, DateNotified, DateOfSale, ProductSoldFor several reasons, there are several "DateNotified"'s attached to each customer ID. I want to bring through the most recent date used only in my results.I've tried :"SELECT CustomerID, DateNotified, DateofSale, ProductSoldFROM dbo.Tbl_Identity INNER JOIN dbo.Tbl_Sales ON dbo.Tbl_Identity.CustomerID = dbo.Tbl_Sales.CustomerIDWhere DateNotified in (select MAX [DateNotified] from Tbl_Identity).Not sure why it won't work. Studio says something about the MAX.Jim |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2014-07-06 : 16:16:37
|
[code]WITH cteSourceAS ( SELECT i.CustomerID, i.DateNotified, s.DateOfSale, s.ProductSold, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY DateNotified DESC) AS rn FROM dbo.Tbl_Identity AS i INNER JOIN dbo.Tbl_Sales AS s ON s.CustomerID = i.CustomerID)SELECT CustomerID, DateNotified, DateOfSale, ProductSoldFROM cteSourceWHERE rn = 1;[/code] Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2014-07-06 : 16:17:20
|
[code]SELECT TOP(1) i.CustomerID, i.DateNotified, s.DateOfSale, s.ProductSoldFROM dbo.Tbl_Identity AS iINNER JOIN dbo.Tbl_Sales AS s ON s.CustomerID = i.CustomerIDORDER BY i.DateNotified DESC;[/code] Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA |
|
|
|
|
|
|
|