sql - MySql: How to group by day and by hour each? SOLVED -
there many questions here posted none one.
what trying query brings me count of records each hour day. see example in table below:
<table> <tr> <th>day/hour</th> <th>0</th> <th>1</th> <th>2</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> <th>14</th> <th>15</th> <th>16</th> <th>17</th> <th>18</th> <th>19</th> <th>20</th> <th>21</th> <th>22</th> <th>23</th> </tr> <tr> <td>2015-06-02</td> <td>12</td> <td>22</td> <td>198</td> <td>234</td> <td>12</td> <td>22</td> <td>198</td> <td>234</td> <td>12</td> <td>22</td> <td>198</td> <td>234</td> <td>12</td> <td>22</td> <td>198</td> <td>234</td> <td>12</td> <td>22</td> <td>198</td> <td>234</td> <td>12</td> <td>22</td> <td>198</td> </tr> <tr> <td>2015-06-01</td> <td>3</td> <td>342</td> <td>1348</td> <td>4</td> <td>3</td> <td>342</td> <td>1348</td> <td>4</td> <td>3</td> <td>342</td> <td>1348</td> <td>4</td> <td>3</td> <td>342</td> <td>1348</td> <td>4</td> <td>3</td> <td>342</td> <td>1348</td> <td>4</td> <td>3</td> <td>342</td> <td>1348</td> <tr> </table>
actually, how should displaying data (the table), how need resulset.
solution:
select date(created_at), count(case hour(created_at) when 0 1 else null end) "0", count(case hour(created_at) when 1 1 else null end) "1", count(case hour(created_at) when 2 1 else null end) "2", count(case hour(created_at) when 3 1 else null end) "3", count(case hour(created_at) when 4 1 else null end) "4", count(case hour(created_at) when 5 1 else null end) "5", count(case hour(created_at) when 6 1 else null end) "6", count(case hour(created_at) when 7 1 else null end) "7", count(case hour(created_at) when 8 1 else null end) "8", count(case hour(created_at) when 9 1 else null end) "9", count(case hour(created_at) when 10 1 else null end) "10" # , 13 more visitas group date(created_at);
since hours in day constant set not change time in foreseeable future, , since want display day-hour combinations no rows too, easiest thing may have 24 columns hardcoded in query:
select date(date_col), count (case hour(date_col) when 0 1 else null end) "0", count (case hour(date_col) when 1 1 else null end) "1", -- 22 more of these my_table group date(date_col)
Comments
Post a Comment