SQL行输出按时间戳分组

时间:2013-07-20 01:42:17

标签: php mysql sql

我有以下表结构:

Time_Stamp  Number
9/07/13     234
9/07/13     345
9/07/13     456
10/07/13    765
10/07/13    834
10/07/13    257

我想像这样打印出来:

9/07/13     234 345 456
10/07/13    765 834 257

任何想法我怎么能去做?

编辑:

这就是我现在打印行的方式:

    if(!$result_db_post = $db->query($query)){
          die('There was an error running the query [' . $db->error . ']');
      }

       while($row = $result_db_post->fetch_assoc()){

          echo $row['time_stamp'] ." ". $row['number'];
          echo "<br />";                               
}

这导致此输出:

    9/07/13 234
    9/07/13 345
    9/07/13 456
   10/07/13 765
   10/07/13 834
   10/07/13 257

我已经尝试了两个查询,两者都会产生相同的输出。

select Time_Stamp, group_concat(Number separator ' ') as Numbers
from t
group by Time_Stamp;

我也尝试过:

SELECT Time_Stamp, GROUP_CONCAT(Number) From table group by Time_Stamp

知道我做错了吗?

2 个答案:

答案 0 :(得分:3)

您似乎希望将数字与原始数据中的顺序相同。但是,SQL表本质上是无序的,因此存在问题。

目前还不清楚您是想将它们放在一列还是三列中。作为一列,您可以使用:

select Time_Stamp, group_concat(Number separator ' ') as Numbers
from t
group by Time_Stamp;

如果您希望将它们分为三列,则可以执行以下操作:

select Time_Stamp,
       substring_index(group_concat(Number), ',', 1) as Number1,
       substring_index(substring_index(group_concat(Number), ',', 2), -1) as Number2,
       substring_index(substring_index(group_concat(Number), ',', 3), -1) as Number3
from t
group by Time_Stamp;

然而,排序是不确定的。

答案 1 :(得分:2)

使用GROUP_CONCAT Function,试试此问题:

SELECT Time_Stamp, GROUP_CONCAT(Number) From table group by Time_Stamp