在 MySQL 中创建交叉表查询

Creating a crosstab query in MySQL

我有一个 MySQL table 可以按一天中的不同时间和不同地点跟踪某些总数。我正在尝试创建一个查询,该查询不仅对每一列进行总计,而且对每一行进行总计。到目前为止,我的查询计算了每一列的总计,但我也不知道如何计算每一行的总计。

这是我的查询:

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')

这最终是我希望输出的样子:

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

我怎样才能做到这一点?

就其价值而言,这不是交叉表查询。您没有将行转为列。

我试过这个查询并得到了你想要的结果:

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;

你真的应该使用 TIME 数据类型而不是字符串。然后它就会正确排序。

+----------+-----------+-----------+-----------+-----------+--------+
| 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 |
+----------+-----------+-----------+-----------+-----------+--------+