简体   繁体   English

SQL行输出按时间戳分组

[英]SQL row output grouped by time stamp

I've got the following table structure: 我有以下表结构:

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

And I would like to print it like this: 我想这样打印:

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

Any idea how i could go about it? 知道我该怎么做吗?

EDIT: 编辑:

This is how I'm printing the rows at the moment: 这是我现在打印行的方式:

    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 />";                               
}

Which results in this output: 结果如下:

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

I've tried both queries and both result in the same output. 我试过两个查询,都导致相同的输出。

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

And I also tried: 我也尝试过:

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

Any idea what I'm doing wrong? 知道我在做什么错吗?

You seem to want to put the numbers in the same order as they are in the original data. 您似乎想按与原始数据相同的顺序排列数字。 However, SQL tables are inherently unordered, so there is an issue. 但是,SQL表本质上是无序的,因此存在问题。

It is unclear whether you want them in one column or three. 目前尚不清楚您是希望将它们放在一列还是三列中。 As one column, you can do it using: 作为一栏,您可以使用:

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

If you want them in three columns, you can do the following: 如果要在三栏中列出它们,可以执行以下操作:

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;

However, the ordering is indeterminate. 但是,顺序是不确定的。

使用GROUP_CONCAT函数 ,请尝试以下查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM