从一列中的唯一值计数向SQL行添加列

时间:2016-04-30 19:28:40

标签: sql ruby-on-rails ruby sqlite

我有两个感兴趣的专栏:

bought_time           |    product
-----------------------------------
1990-10-26T09:00:00Z  | bicycle
1990-10-26T09:00:01Z  | car
1990-10-26T09:13:22Z  | bicycle
1990-10-26T09:26:11Z  | cookies
1990-10-26T09:26:13Z  | milk
1990-10-26T09:27:16Z  | milk

我想在Ruby on Rails中创建一个SQLite查询,它将在被as_json转换后返回:

[{date by minute: 1990-10-26T09:00:00Z, bicycle: 1, car: 1, cookies:0, milk:0}, {date by minute: 1990-10-26T09:13:00Z, bicycle:1, car:0, cookies:0, milk:0}, {date by minute: 1990-10-26T09:26:00Z, bicycle:0, car:0, cookies:1, milk:1}, {date by minute: 1990-10-26T09:26:00Z, bicycle:0, car:0, cookies:0, milk:1} ]

到目前为止,我有类似的内容:

Bought.select("datetime((strftime('%s', date)/60)*60, 'unixepoch') interval, count(type)").where("date(date) >= date(:from) AND date(date) <= date(:to)", {from: event_params["from"], to: event_params["to"]}).order("interval").group("type").group("interval")

SQL中的哪个

SELECT datetime((strftime('%s', date)/60)*60, 'unixepoch') interval, count(type), type FROM "events" WHERE (date(date) >= date('1985-10-26T09:00:00Z') AND date(date) <= date('1985-10-27T09:00:00Z')) GROUP BY interval, "events"."type"  ORDER BY interval

但是我不知道如何从这里开始。

0 个答案:

没有答案