Search code examples
mysqlrollup

Creating a crosstab query in MySQL


I have a MySQL table that tracks certain totals by both hour of the day and various locations. I am trying to create a query that will total not only each column, but also each row. The query I have so far totals each column, but I can't figure out how to get a total for each row as well.

This is my query:

SELECT * FROM
(SELECT IFNULL(hour,"Total") as hour, SUM(location1), SUM(location2), SUM(location3), SUM(location4), SUM(location), FROM counts WHERE ay = 'AY1617' GROUP BY hour WITH ROLLUP) as crossdata
ORDER BY FIELD (hour,'8:00am','9:00am','10:00am','11:00am','12:00pm','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm','9:00pm','10:00pm','11:00pm')

This is ultimately what I want the output to look like:

hour    location1    location2    location3    location4    totals
8am        4              3           2            1           10
9am        1              2           2            1            6
10am       2              3           2            3           10
totals     7              8           6            5           26

How can I achieve this?


Solution

  • For what it's worth, this is not a crosstab query. You aren't pivoting rows to columns.

    I tried this query and got the result you want:

    SELECT IFNULL(hour, 'Total') AS hour, 
      SUM(location1) AS location1, 
      SUM(location2) AS location2, 
      SUM(location3) AS location3, 
      SUM(location4) AS location4, 
      SUM(location1)+SUM(location2)+SUM(location3)+SUM(location4) AS totals 
    FROM counts 
    WHERE ay = 'AY1617' 
    GROUP BY hour WITH ROLLUP;
    

    You should really use the TIME data type instead of strings for the hour. Then it just sorts correctly.

    +----------+-----------+-----------+-----------+-----------+--------+
    | hourt    | location1 | location2 | location3 | location4 | totals |
    +----------+-----------+-----------+-----------+-----------+--------+
    | 08:00:00 |         4 |         3 |         2 |         1 |     10 |
    | 09:00:00 |         1 |         2 |         2 |         1 |      6 |
    | 10:00:00 |         2 |         3 |         2 |         3 |     10 |
    | Total    |         7 |         8 |         6 |         5 |     26 |
    +----------+-----------+-----------+-----------+-----------+--------+