I have a table that is designed like this:
tbl_User
id
Name
tbl_User_Payment
id
user_id
amount
status
tbl_User
id Name
001 John Doe
002 Juan Dela Cruz
tbl_User_Payment
id user_id amount status
001 001 10 Successful
002 002 10 Fail
003 001 10 Fail
004 001 10 Fail
005 001 10 Fail
006 002 10 Successful
007 002 10 Fail
008 002 10 Fail
The problem here is that how can I count the number of Failed Payment after a Successful Payment.
So the result here should be something like this:
John Doe - 3 Failed Payment
Juan Dela Cruz - 2 Failed Payment
I hope you understand what i’m trying to accomplish here.
Your help will be greatly appreciated and rewarded!
Thanks! 🙂
For brevity and clarity, I’m going to alias a few things in my code.
I’m a bit rusty, I haven’t tested this SQL but if it doesn’t work I suspect it’s because of my “
FROM Payments, <subquery>” syntax. I’m not in a position where I can verify my solution, so you might have to recruit someone to help you if it doesn’t work.If you’re wondering, here’s my logic:
SELECT).COUNTof rows, per user, that come after the “last successful payment ID” values that were retrieved by the innermostSELECT.JOINthe results from step 3 with the users table to get the usernames.Also, a few tips for future database design: there is no need to use Hungarian Notation in DB design – I cringe every time I see “tbl_” prefixes. I also advise against naming primary-key fields simply “id” as it makes JOINs more difficult as you need to disambiguate them. Consider prefixing them with the name of the table (e.g. “
payments.id” becomes “Payments.PaymentId“).