Question

I have a table named IJ with a datetime column IJDATE, and varchar columns IJLOC and IJITEM. I need the most recent row for each combination of those two columns (and include the other columns, like IJLCGT, an integer, for the most recent row). So for example, from this data:

IJLOC   IJITEM      IJDATE      IJLCGT
Reno    12X12X12PX  2013-07-29  175705
Reno    12X12X12PX  2013-08-14  125905

I want this result (since it is the most recent row for that combination):

IJLOC   IJITEM      IJDATE      IJLCGT
Reno    12X12X12PX  2013-08-14  125905

I've tried using MAX and grouping the varchar columns, but then I can't include the other columns.

Was it helpful?

Solution

Whoever named your columns needs their knuckles to meet a swiftly moving ruler.

;WITH cte AS 
(
  SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
    rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
  FROM dbo.IJ
)
SELECT IJLOC, IJITEM, IJDATE, IJLCGT
FROM cte WHERE rn = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top