Question: ```
ID  Status      OfferID 
1   Processed   456
1   Processed   123
2   Pending     999
3   Processed   678
3   Pending     789

```

Based on ID,

1. if ID=1 and having same status then output column(CTSDate) should be max of offerID
2. IF ID=2 and having only one status then output is offerID associated with it
3. If ID=3 and having different Status then pick Processed status related OfferID

The above scenario need to be worked for a wholeset of data.

Please help.

Answer: 
We can use `ROW_NUMBER()` here with appropriate sorting levels:

```sql
WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID
                                   ORDER BY Status DESC, OfferID DESC) rn
    FROM yourTable t
)

SELECT ID, Status, OfferID
FROM cte
WHERE rn = 1
ORDER BY ID;

```
I would calculate the max offer id for IDs with processed status and those with no processed status separately and later append them together.

```sql
with tmp1 AS (
  /* cases with processed status */
  SELECT
    ID, max(OfferID) AS OfferID
  FROM 
    tbl
  WHERE status = 'Processed'
  GROUP BY ID
),
tmp2 AS (
  /* cases with no processed status */
  SELECT
    ID, max(OfferID) AS OfferID
  FROM 
    tbl
  WHERE ID NOT IN (SELECT ID FROM tmp1)
  GROUP BY ID
)
SELECT * FROM tmp1
UNION ALL
SELECT * FROM tmp2

```