[英]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我有一个包含 2 列的表,如下所述,我只需要根据给定条件获取行
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.条件:如果 Status 列包含 Success 和 Pending,则仅获取 Success 行并显示。
If the Status column contains Pending and Failed then fetch only Pending rows and display.如果 Status 列包含 Pending 和 Failed,则仅获取 Pending 行并显示。
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 else 条件:
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 !然后唯一的事情就是找到什么标准将 ROW_NUMBER() OVER ORDER BY ???) 作为第一行!
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.
否则返回所有具有最高状态的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.