我似乎无法理解如何使用Rails活动记录查询接口编写以下简单的SQL。
SELECT *
FROM product_sales
WHERE (product_location_id, net_sale)
IN
(
SELECT product_location_id, MAX(net_sale)
FROM product_sales
GROUP BY product_location_id
)
AND (sale_date BETWEEN '2016-05-01' AND '2016-05-31');注意:我看过以下链接。但是,它只在外部WHERE子句中指定了一个列,而我需要两个列。
谢谢你的帮助。
更新
模型
ProductSale
references :product_location, index: true, foreign_key: true
decimal :net_sale, precision: 16, scale: 6
date :sale_dateProductLocation
references :product, index: true, foreign_key: true
etc...关系
ProductSale -> belongs_to :product_location
ProductLocation -> has_many: product_sales请注意,我的数据库在MySQL中。
发布于 2016-05-23 13:54:50
我有另一个建议,试试
用于Postgresql
ProductSale
.select("DISTINCT ON (product_sales.product_location_id), product_sales.*")
.where("product_sales.sale_date BETWEEN '2016-05-01' AND '2016-05-31'")
.order("product_sales.product_location_id, product_sales.net_sale DESC")使用DISTINCT在product_location_id排序的net_sale上从高到低选择uniq行
对于MySQL
sub_query = ProductSale.select("product_location_id, MAX(net_sale) as max_net_sale").where("sale_date BETWEEN '2016-05-01' AND '2016-05-31'").group("product_location_id").to_sql
ProductSale
.joins("INNER JOIN (#{sub_query}) t ON product_sales.product_location_id = t.product_location_id AND product_sales.net_sale = t.max_net_sale")发布于 2016-05-23 14:34:38
查询的第一部分如下,只需使用简单的一对多关系查询,然后加入and条件进行请求:
ProductSale
.where(net_sale: ProductSale.pluck("MAX(net_sale)"))
.and("sale_date BETWEEN ? AND ?", date1, date2)
.where.not(product_location_id: nil)
.group(:product_location_id)https://stackoverflow.com/questions/37392480
复制相似问题