0

I think it's easier to show you an image:

enter image description here

So, for each fld_call_id, go to the next value, if it's identical. When we get to the last value, I need the value in column fld_menu_id.

Or, to put it in another way, eliminate fld_call_id duplicates and save only the last one.

Alexandru Pupsa
  • 1,798
  • 4
  • 21
  • 40

4 Answers4

2

You can use ROW_NUMBER:

WITH CTE AS( 
    SELECT RN = ROW_NUMBER() OVER (PARTITION BY fld_call_id ORDER BY fld_id DESC),
           fld_menu_id
    FROM dbo.TableName
)
SELECT fld_menu_id FROM CTE WHERE RN = 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can create a Rank column and only select that row, something along the lines of the following:

;WITH cte AS
(
 SELECT
  *
  ,RANK() OVER (PARTITION BY fld_call_id ORDER BY fld_id DESC) Rnk
 FROM YourTable
)
SELECT
 *
FROM cte
WHERE Rnk=1

So you GROUP BY fld_call_id and ORDER BY fld_id in descending order so that the last value comes first. These are the rows where Rnk=1.

Edit after comments of OP.

NickyvV
  • 1,720
  • 2
  • 16
  • 18
0
SELECT Table.*
FROM Table
INNER JOIN
(
    SELECT MAX(fldMenuID) AS fldMenuID,
    fldCallID
    FROM Table
    GROUP BY fldCallID
) maxValues
ON (maxValues.fldMenuID = Table.fldMenuID
AND maxValues.fldCallID= Table.fldCallID)
0

Hope This works

SELECT  A.*
FROM    table A
JOIN    (SELECT fld_id,
                ROW_NUMBER() OVER (PARTITION BY Fld_call_id ORDER BY fld_id DESC) [Row]
        FROM    table) LU ON A.fld_id = LU.fld_id
WHERE   LU.[Row] = 1
Jithin Shaji
  • 5,893
  • 5
  • 25
  • 47