2013-07-27 58 views
0

我有如下表:SQL命令按天來概括/月

+----+---------------------+-------------+-----------------+ 
| id | stat_time   |  reads |   writes | 
+----+---------------------+-------------+-----------------+ 
| 1 | 2013-07-18 20:00:00 | 42614543 |   1342129 | 
| 2 | 2013-07-18 21:00:00 | 23085319 |   326139 | 
| 3 | 2013-07-25 12:00:00 |   0 |   39639 | 
| 4 | 2013-07-25 13:00:00 |  754166 |   39639 | 
| 5 | 2013-07-25 14:00:00 |  693382 |   295323 | 
| 6 | 2013-07-25 15:00:00 |  1334462 |    0 | 
| 7 | 2013-07-25 16:00:00 | 10748367 |   261489 | 
| 9 | 2013-07-25 17:00:00 |  4337294 |    0 | 
| 10 | 2013-07-25 18:00:00 |  3002796 |    0 | 
| 11 | 2013-07-25 20:00:00 |  3002832 |    0 | 
| 12 | 2013-07-25 23:00:00 |   0 |   333468 | 
| 13 | 2013-07-26 17:00:00 | 10009585 |    0 | 
| 15 | 2013-07-26 18:00:00 |  6005752 |    0 | 
| 17 | 2013-07-26 21:00:00 |  333663 |    0 | 
+----+---------------------+-------------+-----------------+ 

我想是這樣執行的東西:

SELECT stat_time, SUM(reads), SUM(writes) from this_table GROUP BY stat_time HAVING 'the same day'..

所以其輸出三行命令(一個用於2013-07-18,第二個用於2013-07-25,第三個用於2013-07-26),並且在列中的每個這樣的行中讀取/寫入在當天存在讀取/寫入的總和。

謝謝 大衛

回答

9

希望將stat_time轉換爲一天做到這一點。該方法取決於數據庫。這裏有一種方法:

SELECT cast(stat_time as date) as stat_day, SUM(reads), SUM(writes) 
from this_table 
GROUP BY cast(stat_time as date) 
order by stat_day; 

這裏有一些其他的方法(用於MySQL和Oracle):

SELECT date(stat_time) as stat_day, SUM(reads), SUM(writes) 
from this_table 
GROUP BY date(stat_time) 
order by stat_day; 

SELECT trunc(stat_time) as stat_day, SUM(reads), SUM(writes) 
from this_table 
GROUP BY trunc(stat_time) 
order by stat_day; 
+0

它看起來完美!謝謝。這是對MySQL的查詢,那麼如果我給它一個參數2013-07-26什麼是函數2013-07-26 17:00:00(同一個月的問題,所以返回值等於2013- 07)。再次感謝。 – user2042985

+0

@ user2042985。 。 。中間的查詢是MySQL語法。該函數是'date()'。 –

+0

謝謝戈登! – user2042985

0

讓我們假設你有一個列名稱爲d-DATE_START所以

$query = 'SELECT cast(D_DATE_START as date) as stat_day ,' 
     .'sum(I_REV_MODEL) as totalDayRevenu ' 
     .'FROM t_show WHERE FK_MODEL=136 ' 
     ."and t_show.D_DATE_START between '".$after."' and '".$before."'" 
     .' GROUP BY cast(D_DATE_START as date) ' 
     .' ORDER BY stat_day ';