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 columnsplaID
andcouID
regarding the plan and course, respectively, how you will identify whether it was a course or a enrolled plan?– RXSD
I did not understand very well this modeling of the table subscriptionPlan, it is possible to buy only one course or only one plan?
– RXSD
@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.
– Maykel Esser