简体   繁体   中英

Based on multiple status, pick specific date column in sql

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM