Mysql Pivot / Crosstab query

Hello,

I have 2 tables of teachers  and lessons in an online tuition center, like below:

Teachers Table:
+----+--------+
| id|name |
+----+--------+
| 1 | John  |
| 2 | Mike |
| 3 | Bill    |
+----+--------+

Lessons Table:
+----+------------------------------+--------------+--------------+
| id | booking_time            | teacher   | student  |
+----+------------------------------+--------------+--------------+
| 1 | 2017-08-08 12:00:00 | 3              | 40            |
| 2 | 2017-10-03 12:00:00 | 1              | 50            |
| 3 | 2017-12-01 12:00:00 | 2              | 60            |
| 4 | 2018-01-01 12:00:00 | 3              | 40            |
| 5 | 2018-02-01 12:00:00 | 2              | 60            |
| 6 | 2018-03-02 12:00:00 | 3              | 40            |
| 7 | 2018-03-04 12:00:00 | 1              | 50            |
| 8 | 2018-03-06 12:00:00 | 1              | 50            |
+---+-------------------------------+--------------+--------------+

I need to get each teacher's total booked lessons in the last 12 months (starting from current month) and sorted by the current month's highest bookings. Something like:

+--------------+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
| Teacher   | Mar-18 | Feb-18 | Jan-18 | Dec-17 |Nov-17| Oct-17 | Sep-17 |Aug-17 | Jul-17  | Jun-17 | May-17 |Apr-17 |
+--------------+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
| John        | 2            | 0           | 0          | 0           | 0          | 1           | 0          | 0           | 0          | 0           | 0          | 0           |
| Bill           | 1            | 0           | 1          | 0           | 0          | 0           | 0          | 1           | 0          | 0           | 0          | 0           |
| Mike        | 0            | 1           | 0          | 1           | 0          | 0           | 0          | 0           | 0          | 0           | 0          | 0           |
+--------------+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+------------+

Any help how I can do this please?
hennanraAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulEE Topic AdvisorCommented:
Use "conditional aggregates" as such as this:
SELECT
     t.id,  t.name
    , COUNT(CASE WHEN l.booking_time >= '2017-03-01' AND l.booking_time < '2017-04-01' THEN l.teacher END) AS "2017-03"
    , COUNT(CASE WHEN l.booking_time >= '2017-04-01' AND l.booking_time < '2017-05-01' THEN l.teacher END) AS "2017-04"
    , COUNT(CASE WHEN l.booking_time >= '2017-05-01' AND l.booking_time < '2017-06-01' THEN l.teacher END) AS "2017-05"
    , COUNT(CASE WHEN l.booking_time >= '2017-06-01' AND l.booking_time < '2017-07-01' THEN l.teacher END) AS "2017-06"
    , COUNT(CASE WHEN l.booking_time >= '2017-07-01' AND l.booking_time < '2017-08-01' THEN l.teacher END) AS "2017-07"
    , COUNT(CASE WHEN l.booking_time >= '2017-08-01' AND l.booking_time < '2017-09-01' THEN l.teacher END) AS "2017-08"
    , COUNT(CASE WHEN l.booking_time >= '2017-09-01' AND l.booking_time < '2017-10-01' THEN l.teacher END) AS "2017-09"
    , COUNT(CASE WHEN l.booking_time >= '2017-10-01' AND l.booking_time < '2017-11-01' THEN l.teacher END) AS "2017-10"
    , COUNT(CASE WHEN l.booking_time >= '2017-11-01' AND l.booking_time < '2017-12-01' THEN l.teacher END) AS "2017-11"
    , COUNT(CASE WHEN l.booking_time >= '2017-12-01' AND l.booking_time < '2018-01-01' THEN l.teacher END) AS "2017-12"
    , COUNT(CASE WHEN l.booking_time >= '2018-01-01' AND l.booking_time < '2018-02-01' THEN l.teacher END) AS "2018-01"
    , COUNT(CASE WHEN l.booking_time >= '2018-02-01' AND l.booking_time < '2018-02-01' THEN l.teacher END) AS "2018-02"
FROM teachers t
WHERE l.booking_time >= '2017-03-01' and l.booking_time < '2018-02-01'
LEFT JOIN lessons l ON t.id = l.teacher
GROUP BY
      t.id, t.name
;

Open in new window

In these queries a case expression is used INSIDE an aggregate function (the case expression provides the "condition" hence "conditional aggregates"). Here we use COUNT() as the aggregate, and not that count ignores NULL (i.e. only counts non-null values that it encounters).

For a brief outline of making such a query "dynamic" see: http://webdevzoom.com/dynamic-pivot-table-using-mysql/

Please also note I have not use "between" in the case expressions, and this is deliberate, for more on this topic please see: "Beware of Between"

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201'
This form works with all types and all precisions, regardless of whether the time part is applicable.
Itzik Ben-Gan
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hennanraAuthor Commented:
It worked!!!

Thank you so much for the comprehensive answer!
0
PortletPaulEE Topic AdvisorCommented:
Thanks. At Experts-Exchange you are expected to "close" (accept) questions when they are answered.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.