MYSQL - Query to bring the best-selling plans and courses, with different groupby

Asked

Viewed 27 times

1

I sell subscriptions to my course online, and also the courses separately.

I’d like to bring the top 5 best selling plans/courses. For this, I have a table called subscriptionPlan, who guards the id of the plan purchased, or in the case of a course, the id of this, and the amount spent on this transaction. Example:

Table subscriptionPlan:

sbpId | subId | plaId | couId | sbpAmount
1     | 1     | 1     | 1     | 499.99
2     | 2     | 1     | 2     | 499.99
3     | 3     | 2     | 0     | 899.99
4     | 4     | 1     | 1     | 499.99

For educational purposes only, plaId = 1 is a plan called Loose sale that I created to maintain the integrity of the bank. When there is a couId completed, which also means that a one-off course has been purchased, not a plan where they can attend any course.

I reiterate my need: List the top 5 sales. If it is a plan, display the plan name (table plan, spine plaTitle). If it is a course, display its name (table Course, spine couTitle). This logic I can’t quite put together.

I managed to assemble a top 5 of PLANS, but it groups the courses, since the GROUP BY is by plan ID. I believe the move is here, create a IF/ELSE in this GROUPBY, but then I don’t know what to do.

The query I created, which groups the plans is this:

SELECT sp.plaId, sp.couId, p.plaTitle, p.plaPermanent, c.couTitle, SUM(sbpAmount) AS sbpTotalAmount
FROM subscriptionPlan sp
LEFT JOIN plan p ON sp.plaId = p.plaId
LEFT JOIN course c ON sp.couId = c.couId
GROUP BY sp.plaId
ORDER BY sbpTotalAmount DESC
LIMIT 5

The result I need would be:

plaId | couId | plaTitle        | couTitle   | plaPermanent | sbpTotalAmount
1     | 1     | Venda avulsa    | Curso 01   | true         | 999.98
2     | 0     | Acesso total    | null       | false        | 899.99
1     | 2     | Venda avulsa    | Curso 02   | true         | 499.99

How could I get into this formula?

  • If on your table subscriptionPlan there are columns plaIDand couID regarding the plan and course, respectively, how you will identify whether it was a course or a enrolled plan?

  • I did not understand very well this modeling of the table subscriptionPlan, it is possible to buy only one course or only one plan?

  • @Andréfilipe You can purchase a plan (to attend all courses), or a one-off course. When purchasing a one-off course, I assign Plaid = 1 (which is a plan called One-off Purchase). Therefore, if couId is non-zero, it also means that it was a one-off purchase, even if you have a completed plan.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.