sql - 带有 in group by 或 partition by 子句的 case 语句

标签 sql postgresql plsql plsqldeveloper

Customer   Decision      req_date   
   A       Approved     2017-06-13
   A       Approved     2017-06-13
   A       Pending      2017-06-13
   B       Pending      2017-10-13
   B       Approved     2017-06-13
   C       Pending      2017-07-14

对于给定的客户 ID,

如果决定是已批准的,则只保留客户的批准行。如果客户没有任何已批准的决定,则保留客户的所有行。

期待输出

Customer   Decision      req_date   
   A       Approved     2017-06-13
   A       Approved     2017-05-13
   B       Approved     2017-06-13
   C       Pending      2017-07-14

最佳答案

我会使用:

select t.*
from t
where t.decision = 'Approved' or
      not exists (select 1
                  from t t2
                  where t2.Customer = t.Customer and t2.decision = 'Approved'
                 );

关于sql - 带有 in group by 或 partition by 子句的 case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831054/

相关文章:

Java 将值传递到 SQL WHERE 子句中的 IN

sql - PostgreSQL 查找重复字段

sql - 在 oracle 中使用无效的包引用选择查询

具有不同表名且仅特定列的 MySQL 复制

sql - 选择仅与另一个表中的记录相关联的记录

sql - 无法从 C 连接到数据库

java - 从 ResultSet 按行读取数据

regex - IPv6 正则表达式 (RegEx) 在 PL/SQL 中不起作用

sql - 如何在 Oracle 中查询 CLOB 列

mysql - 跨多个服务器连接表