1

I have three tables. Each User can have multiple Subscriptions and each Subscription can have multiple Payments.

Me goal is to count all Payments for a single User using one SQL query. Is it possible to do and how?

In the case below, The result for a User with id 1 should be 2 (because the User has two Payments)

Users
+----+------+
| Id | Name |
+----+------+
| 1  | John |
+----+------+

Subscriptions
+----+--------+-----------+
| Id | userId |   data    |
+----+--------+-----------+
| 1  |   1    | some data |
+----+--------+-----------+
| 2  |   1    | some data |
+----+--------+-----------+

Payments

+----+----------------+--------+
| Id | subscriptionId | amount |
+----+----------------+--------+
| 1  |        1       |   30   |
+----+----------------+--------+
|  2 |        2       |   50   |
+----+----------------+--------+
0

2 Answers 2

3

try like below by using join and aggregation

SELECT u.id, u.Name, COUNT(p.id) AS numberofpayment
FROM users u
  Left JOIN Subscriptions s ON u.Id=s.userId
  Left JOIN Payments p ON s.id=p.subscriptionId
GROUP BY u.id, u.Name
Sign up to request clarification or add additional context in comments.

5 Comments

Might be best to use LEFT OUTER JOINs to allow a count of 0 when the user exists but has no payments.
@Kickstart This answer is good to count all Payments for a single User.
@VladimirKovpak - if the user has no subscriptions or no payments the query as it stands will return no rows, rather than a row for the user with a count of 0.
@Kickstart Yes, true... It's better to use LEFT JOIN.
Hey guys thanks I edited you are right left is more meaningful
1

You can try to do something like this:

SELECT COUNT(p.Id) AS PaymentCount
FROM Users u
  LEFT JOIN Subscriptions s ON u.Id=s.userId
  LEFT JOIN Payments p ON s.id=p.subscriptionId
WHERE u.Id = @yourUserID

Pay attention on COUNT(p.Id) - it means count of existing payments.

PS: this answer for @Kickstart.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.