2017-09-26 232 views
1

我有一個MySQL表,可以在一天中的不同時間點和不同位置跟蹤某些總計。我試圖創建一個查詢,不僅將每個列,而且每個行。我到目前爲止的查詢總計每列,但我無法弄清楚如何獲得每行的總數。在MySQL中創建交叉表查詢

這是我的查詢:

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 

我怎樣才能做到這一點?

回答

1

值得一提的是,這不是交叉表查詢。你沒有將行轉換爲列。

我嘗試此查詢並得到結果,你想:

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