正如标题所示,我想选择用a组成的每组行的第一行GROUP BY.
具体来说,如果我有一个purchases看起来像这样的表:
SELECT * FROM purchases;
Run Code Online (Sandbox Code Playgroud)
我的输出:
id | customer | total ---+----------+------ 1 | Joe | 5 2 | Sally | 3 3 | Joe | 2 4 | Sally | 1
我想查询每个产品id的最大购买量(total)customer.像这样的东西:
SELECT FIRST(id), customer, FIRST(total)
FROM purchases
GROUP BY customer
ORDER BY total DESC;
Run Code Online (Sandbox Code Playgroud)
预期产出:
FIRST(id) | customer | FIRST(total)
----------+----------+-------------
1 | Joe | 5
2 | Sally | 3
我需要按日期/时间字段对PostgreSQL表进行排序,例如last_updated.
但是,该字段允许为空或空,我想与空记录last_updated来之前,非空last_updated.
这可能吗?
order by last_updated asc /* and null last_updated records first ?? */
Run Code Online (Sandbox Code Playgroud) 我的控制器中的代码是按照最高的平均评价等级对相册进行排名(使用此解决方案中的代码如何通过has_many评论关系显示评分最高的专辑):
@albums = Album.joins(:reviews).select("*, avg(reviews.rating) as average_rating").group("albums.id").order("average_rating DESC")
Run Code Online (Sandbox Code Playgroud)
这段代码在我的开发环境(sqlite3)中完美运行,但是当我将代码推送到heroku和postgresql时,我遇到了这个错误:
PG::GroupingError: ERROR: column "reviews.id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)
我意识到这是一个相当普遍的问题,我对SQL有点缺乏经验,因此我无法重构代码,因此它可以在我的开发和生产环境中工作.
sqlite postgresql activerecord ruby-on-rails ruby-on-rails-4
我使用SQLite3进行开发,使用PostgreSQL进行部署.但是,我面临以下问题:
我的简单搜索使用SQLite3:
def self.search(search)
if search
find(:all, :conditions => ["style LIKE ? OR construction LIKE ?", "%#{search}%", "%#{search}%"])
else
find(:all)
end
end
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用PostgreSQL,我需要替换LIKEfor ILIKE来解决问题:
def self.search(search)
if search
find(:all, :conditions => ["style ILIKE ? OR construction ILIKE ?", "%#{search}%", "%#{search}%"])
else
find(:all)
end
end
Run Code Online (Sandbox Code Playgroud)
是否有"Ruby方式"在任何数据库中进行这些搜索?
编辑 - 基于您的答案我不相信我会找到一个通用的Ruby解决方案.
我也跟着Ruby on Rails的教程:学习的榜样导轨-由迈克尔·哈特尔,在最终的Gemfile显示这两个数据库...嗯,令人失望...
我有这三个模型:
class Order
has_many :items
end
class Item
belongs_to :order
belongs_to :product
end
class Product
has_many :orders, through: :items
has_many :items
end
Run Code Online (Sandbox Code Playgroud)
我需要列出给定日期范围内订单中每种产品的数量.
我有一个范围来获取日期范围内的所有订单:
Order.date_range(from, to)
Run Code Online (Sandbox Code Playgroud)
现在我需要分组和数数; 项目模型上有字段product_id和units字段.
我见过解决方案,但只有两个表(订单>产品)而不是三个(订单>商品>产品).