简体   繁体   中英

Fetch only selected rows based on the given condition in SQL Query #sql

I've a table with 2 columns as mentioned below, and I need to fetch only the rows based on the given conditions

Table

Id Status
1 Success
2 Failed
3 Success
4 Pending
5 Success
6 Failed
7 Pending
8 Failed
9 Success
10 Pending

Conditions: If the Status column contains Success and Pending then fetch only Success rows and display.

If the Status column contains Pending and Failed then fetch only Pending rows and display.

If the Status columns only Failed then fetch and display 1st row alone.

SELECT id, Status
from table1
where status = "Success";

Sample Pseudo Code:

I've made a simple if else condition for better understanding:

If (status = Success or Pending){
    return Success rows
}
else if(Status = success or failed){
    return Success rows
}
else if( status = pending or failed){
    return pending rows
}
else if(!status = success or pending){
    return First row
}
else if (status = success or pending or failed){
    return Success rows
}

Thanks in advance

WITH T AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY ???) AS RN,
       CASE WHEN status <> 'Success' and status <> 'Pending'
                       THEN 1 ELSE 0 
       END AS FIRST_ROW
WHERE status = CASE WHEN status = 'Success' or status = 'Pending'
                       THEN 'success'
                    WHEN status = 'Success' or status = 'Fail'
                       THEN 'success'
                    WHEN status = 'pending' or status = 'Fail'
                       THEN 'pending'
                    WHEN status <> 'Success' and status <> 'Pending'
                       THEN status 
                   WHEN status = 'Success' or status = 'Pending' or status = 'failed'
                       THEN 'success'
               END
)
SELECT *
FROM   T
WHERE  RN = CASE FIRST_ROW WHEN 1 THEN 1 ELSE RN END

Then only thing is to find what criteria will have the ROW_NUMBER() OVER ORDER BY ???) as first row !

By the way some filters are contradictive...

'Success' > 'Pending' > 'Failed'.

SELECT t1.id, t1.Status
from table1 t1
join (select min(id) minid, max(status) maxstatus from table1) t2
  on (t2.maxstatus = 'Failed' and t1.id = t2.minid) or
     (t2.maxstatus <> 'Failed' and t1.status = t2.maxstatus)

Return the first row only when only Failed rows. Otherwise return all rows having the highest status.

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