简体   繁体   English

在 MySQL 中创建交叉表查询

[英]Creating a crosstab query in MySQL

I have a MySQL table that tracks certain totals by both hour of the day and various locations.我有一个 MySQL 表,它按一天中的小时和各个位置跟踪某些总数。 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?我怎样才能做到这一点?

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.您应该真正使用TIME数据类型而不是小时的字符串。 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 |
+----------+-----------+-----------+-----------+-----------+--------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM