---
title: "按时间段分组"
author: "夜鸣猪"
date: "2011-12-02T23:44:41Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-12-02T23:44:41Z"
id: 1290341
url: "https://hlee.iteye.com/blog/1290341"
---

PostgreSQL：

```ruby
User.count(:order => 'DATE(created_at) DESC', :group => ["date(created_at)"])
```



```ruby
User.count(:order => 'DATE(created_at) DESC', :group => ["date(created_at)"]).each {|u| puts "#{u[0]} -> #{u[1]}" }
```




```ruby
Foo.order("DATE(start_at)").group("DATE(start_at)").count
```


Mysql在另一篇，heroku啊，让我学习postgresql


```ruby

select floor(datediff(now(), created) / 3) * 3 as days_ago
      ,min(created)
      ,max(created)
      ,count(*)
  from t1
 group 
    by floor(datediff(now(), created) / 3);


```



<https://github.com/Bantik/seer>


```ruby

# declare a struct to hold the results
UserCountByDate = Struct.new(:date, :count) 

def report
  @user_counts = User.count( :group => "DATE(created_at)", 
                   :conditions => ["created_at >= ? ", 7.days.ago], 
                   :order => "DATE(created_at) ASC"
                 ).collect do |date, count| 
                   UserCountByDate.new(date, count)
                 end

end


```



```html

<div id="chart"></div>

<%= Seer::visualize(
      @user_counts, 
      :as => :column_chart,
      :in_element =>'chart', 
      :series => {
        :series_label => 'date',
        :data_method => 'count'
      },
      :chart_options => {
        :height => 300,
        :width => 100 * @user_counts.size,
        :is_3_d => true,
        :legend => 'none',
        :colors => "[{color:'#990000', darker:'#660000'}]",
        :title => "New users in last 7 days",
        :title_x => 'date',
        :title_y => 'count'
      }
    )
 -%>

```