繁体   English   中英

根据 SQL Query #sql 中的给定条件仅获取选定的行

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

我有一个包含 2 列的表,如下所述,我只需要根据给定条件获取行

桌子

ID 地位
1 成功
2 失败的
3 成功
4 待办的
5 成功
6 失败的
7 待办的
8 失败的
9 成功
10 待办的

条件:如果 Status 列包含 Success 和 Pending,则仅获取 Success 行并显示。

如果 Status 列包含 Pending 和 Failed,则仅获取 Pending 行并显示。

如果仅状态列失败,则单独获取并显示第一行。

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

示例伪代码:

为了更好地理解,我做了一个简单的 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
}

提前致谢

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

然后唯一的事情就是找到什么标准将 ROW_NUMBER() OVER ORDER BY ???) 作为第一行!

顺便说一句,有些过滤器是矛盾的...

“成功”>“待定”>“失败”。

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)

仅当只有失败的行时才返回第一行。 否则返回所有具有最高状态的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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