简体   繁体   English

SQL查询时间戳记日期字段并将所有结果按日期分组

[英]SQL Query timestamp date field and group all results by date

I'm trying to create a list and i'm being stumped. 我正在尝试创建列表,但我很困惑。 So I have a table that with a start_date field that holds Unix Timestamps for the date. 因此,我有一个带有start_date字段的表,其中包含用于日期的Unix时间戳。 I'm trying to query the table and extract the date from the timestamp, then any result with that date will be under that day and so on. 我正在尝试查询表并从时间戳中提取日期,那么具有该日期的任何结果都将在该天之内,依此类推。 Almost like a calendar with events on it in list view. 就像日历在列表视图中具有事件一样。

I'm doing this with PostgreSQL and PHP. 我正在使用PostgreSQL和PHP。 Not sure how to write that query. 不确定如何编写该查询。 I see functions like extract, date_part etc for PostgreSQL however, still unsure how to get the correct query(s). 我看到诸如PostgreSQL的extract,date_part等函数,但是仍然不确定如何获取正确的查询。

Any help or examples would be appreciated. 任何帮助或示例,将不胜感激。

date('d M Y', $timestamp); should give you the date, month and year of that particular UNIX timestamp. 应该为您提供该特定UNIX时间戳记的日期,月份和年份。

If you would like to have it in a list view, run a select query on the database order by start_date field (ascending or descending), and fetch it in $row. 如果要在列表视图中使用它,请按start_date字段(升序或降序)对数据库顺序运行一次select查询,然后在$ row中获取它。 Then inside the loop where you process the record one by one, do this: 然后在循环中处理记录的一个循环中,执行以下操作:

$prevDate = ' ';
$currentDate = ' ';

for each ( $row ) //however it goes
{
    $currentDate = date('d M Y',$row['start_date']);
    if($prevDate != $currentDate)
    {
        echo "Day : ".$currentDate;
    }
    echo $row['other-fields'];
    $prevDate = $currentDate;
 }

However, PostgreSQL supports date datatype, and using that should simplify things at your end. 但是,PostgreSQL支持date数据类型,使用它可以简化您的工作。

http://www.postgresql.org/docs/8.2/static/datatype-datetime.html http://www.postgresql.org/docs/8.2/static/datatype-datetime.html

Simplest / fastest way to extract a date from a Unix epoch: 从Unix时代提取date最简单/最快的方法:

SELECT to_timestamp(my_epoch_ts)::date;

Example: 例:

SELECT to_timestamp(1349118398)::date

Result: 结果:

2012-10-01

That's making use of the to_timestamp() function, followed by a cast to date: ::date . 这是利用to_timestamp()函数,然后使用to_timestamp() 为date ::date

More details and links at the end of this recent related answer . 此最新答案的末尾有更多详细信息和链接。

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

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