【问题标题】:MYSQL basic conditional aggregation for same ColumnsMYSQL 相同列的基本条件聚合
【发布时间】:2021-04-17 17:44:25
【问题描述】:

我有以下问题,我不知道我该如何解决。

我需要根据两个条件+相同属性进行过滤

获取事件为“paymentFailed”且事件不是“paymentSuccess”的用户

  • 基本上我需要为每个用户过滤所有“失败的付款”,但条件意味着同一用户不能存在 paymentSuccess。

  • 如果用户存在 paymentSuccess,结果应该为空。

id  name    event             transaction_number    
2   John    paymentFailed         002   
3   John    paymentInProcess      003   
4   John    paymentStucked        004   
5   John    paymentSuccess        005   
6   Jane    paymentFailed         006   
7   Jane    paymentSuccess        007   
8   Reese   paymentFailed         008   
9   Reese   paymentFailed         009   
10  Reese   otherPayment          010   

类似这样的事情(当 paymentSuccess 不存在时)

SELECT * FROM USERS where event != "paymentSuccess" AND event = "paymentFailed"

结果:

id  name    event             transaction_number    
8   Reese   paymentFailed         008   

并且(当 paymentSuccess 存在时)

SELECT * FROM USERS where event = "paymentSuccess" AND event = "paymentFailed"

结果:

id  name    event             transaction_number    
------------------------ Empty table -----------------------

【问题讨论】:

    标签: mysql conditional-statements aggregation querying


    【解决方案1】:

    使用NOT EXISTS:

    SELECT u1.* 
    FROM USERS u1 
    WHERE u1.event = 'paymentFailed'
      AND NOT EXISTS (SELECT 1 FROM USERS u2 WHERE u2.name = u1.name AND u2.event = 'paymentSuccess')
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多