ID Status OfferID
1 Processed 456
1 Processed 123
2 Pending 999
3 Processed 678
3 Pending 789
Based on ID,
The above scenario need to be worked for a wholeset of data.
Please help.
We can use ROW_NUMBER()
here with appropriate sorting levels:
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.
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
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.