title: MySQL - Top 5 rank best seller plans or courses
body: <p>I sell subscriptions of my online course, as well as the courses in retail.
  I would bring the "top 5" of best selling plans / courses. For this, I have a table called "subscriptionPlan", which stores the purchased plan ID, or in the case of a course, the course ID, and the amount spent on this transaction. Example:</p>
  
  <p><strong>table subscriptionPlan</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p>Just for educational purposes, plaId = 1 is a plan called "Single Sale" that I created, to maintain the integrity of the DB. When the couId isn't empty, you also have bought a separate course, not a plan where you can attend any course.</p>
  
  <p>My need is: List the top 5 sales. If it is a plan, display the plan name (plan table, column plaTitle). If it is a course, display its name (table course, colna couTitle). This logic that I can't code. I was able to rank a top 5 of PLANS, but it groups the courses, since the GROUP BY is by the ID of the plan. I believe the prank is here, maybe creating an IF / ELSE in this GROUPBY, but I don't know how to do this.</p>
  
  <p>The query that i code, to rank my top 5 plans is:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The result that i expected was:</p>
  
  <pre><code>plaId | couId | plaTitle        | couTitle   | plaPermanent | sbpTotalAmount
  1     | 1     | Venda avulsa    | Curso 01   | true         | 999.98
  2     | 0     | Acesso total    | null       | false        | 899.99
  3     | 2     | Venda avulsa    | Curso 02   | true         | 499.99
  </code></pre>
  
  <p>How could I get into this query formula?</p>