MySql:如何按天和小时分组?

时间:2015-06-02 16:26:42

标签: mysql sql select

我想要做的是一个查询,每天每小时都会记录所有记录。参见下表中的示例:

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

实际上,这正是我应该如何显示数据(表格),以及我如何需要结果集。

1 个答案:

答案 0 :(得分:0)

由于一天中的小时数是一个在可预见的未来不会随时改变的常数,因为您可能希望显示没有行的日间小时组合,最简单的方法可能就是拥有24列在您的查询中硬编码:

SELECT   DATE(date_col),
         COUNT (CASE HOUR(date_col) WHEN 0 THEN 1 ELSE NULL END) AS "0",
         COUNT (CASE HOUR(date_col) WHEN 1 THEN 1 ELSE NULL END) AS "1",
         -- 22 more of these
FROM     my_table
GROUP BY DATE(date_col)