Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

MYSQL basic conditional aggregation for same Columns

i have the following issue and i don't know how can i achieve that.

I need to filter based on both conditions + same property

Get Users where the event is "paymentFailed" and event is not "paymentSuccess"

  • Basically i need to filter all "Failed Payments" for every user, but the condition implies that a paymentSuccess must not exist for the same user.

  • If the paymentSuccess exists for the user, the result should be empty.

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   

Something like this (when paymentSuccess does not exists)

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

Result:

id  name    event             transaction_number    
8   Reese   paymentFailed         008   

And (when paymentSuccess exists)

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

Result:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use 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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...