Tag: sql

Rails按has_many的聚合进行选择和排序

我有一个课程模型,有很多评论。 我的评论模型有一个评级字段。 我想要的是查询最受好评的课程。 我想在SQL中执行此操作,以避免返回所有课程对象,然后尝试对它们进行排序和排序。

从范围记录计算总数百分比并显示虚拟属性(Rails / Active Record)

创建一个范围,可能是这样的.. scope :mv, select(‘*,quantity*market_price as market_value, quantity*market_price/sum(quantity*market_price) as percent’) 这会创建两个虚拟属性,market_value和percent。 我遇到的问题是创建包含sum()的百分比。 如果我添加sum(),则范围返回一条记录。 我需要计算相对于范围记录集的总市值的market_value的百分比。 例: 1, market_value: 100, percent: .10 2, market_value: 100, percent: .10 3, market_value: 100, percent: .10 4, market_value: 100, percent: .10 5, market_value: 100, percent: .10 6, market_value: 500, percent: .50 Total is 1000 但是,如果我将其范围扩大到market_value <6,我应该看到 1, market_value: 100, percent: .20 2, […]

如何调整ActiveRecord(或直接SQL)查询以包含带有WHERE子句的JOIN上的零计数记录

我有一个关于在ActiveRecord中形成查询的问题,但也为那些不熟悉ActiveRecord的人提供了SQL。 我有以下模型类: class Shoe < ActiveRecord::Base has_many :purchases def self.available_shoes #show all shoes that have been purchased less than num_in_stock num_in_stock = 3 Shoe.includes(:purchases) .group("purchases.shoe_id") .having("COUNT(purchases.shoe_id) < ?", num_in_stock) end def self.available_shoes_for_user(user) #show all available_shoes that a user hasn't already purchased Shoe.available_shoes.where("purchases.user_id != ?", user.id) end end 方法Shoe.available_shoes按预期工作,因为它将返回购买的所有鞋子的次数少于库存中可用的数量(在这种情况下为3),包括已购买零次的鞋子。 当我打电话给Shoe.available_shoes_for_user(user)时会出现问题,它会显示所有已购买的鞋子,但它没有显示零购买的鞋子。 我已经解压缩了下面的原始SQL: #Shoe.available_shoes SELECT shoes.*, purchases.* FROM […]

使用SET将复杂的SQL查询转换为Arel或Squeel

如何使用AREL或Squeel翻译给定查询: SET @start = ‘2013-05-14’; SET @end = ‘2013-11-01’; SET @days = DATEDIFF(@end, @start); SET @UnusedDays = 0; SELECT @UnusedDays := DATEDIFF(end_at,@end) FROM PERIODS WHERE (@end > start_at AND @end = start_at AND @start = start_at AND @start < end_at) OR (end_at @start) OR (@end > start_at AND @end <= end_at); 将它用作原始SQL的解决方案也将受到欢迎,因为到目前为止我无法运行它。 更新:在SQL请求中描述期间模型和目标, 以查找是否完全覆盖了期间 UPDATE2:如果我尝试使用原始的SQL查询,如: […]

内部mysql case语句未在结果中显示时不匹配

我有一个mysql语句如下 SELECT CASE WHEN HOUR(created_at) BETWEEN 0 AND 11 THEN ‘Morning’ WHEN HOUR(created_at) BETWEEN 12 AND 15 THEN ‘Afternoon’ WHEN HOUR(created_at) BETWEEN 16 AND 18 THEN ‘Evening’ WHEN HOUR(created_at) BETWEEN 19 AND 24 THEN ‘Night’ END AS session, SUM(total) AS `total` FROM `orders` WHERE (purchase_date between ‘2014-05-01’ and ‘2014-05-30’) GROUP BY CASE WHEN HOUR(created_at) BETWEEN […]

rails sum多个字段

我试图在rails中做这个假设简单的操作: self.timesheets.select(“sum(total) as total, sum(quantity) as quantity”).first where self is a project 当我在控制台模式下执行它时,它可以工作,但它呈现3列: [#] 当我在应用程序中运行它时,我收到此错误消息: PG::GroupingError – ERROR: column “timesheets.id” must appear in the GROUP BY clause or be used in an aggregate function LINE 1: …” WHERE “timesheets”.”project_id” = $1 ORDER BY “timesheet… ^ : activerecord (4.0.0) lib/active_record/connection_adapters/postgresql_adapter.rb:811:in `prepare_statement’ activerecord (4.0.0) lib/active_record/connection_adapters/postgresql_adapter.rb:772:in `exec_cache’ schema_plus […]

Rails – SQL查询返回所有指定相关对象的对象(has_many through)

这是我的第一个问题。 我想构建一个查询,它将为我提供具有所有指定function的所有主题。 我有三个模型主题,function和ThemeFeatures 主题has_many:features,:through =>:theme_feautures 可以说DB中有一个Theme对象(id:1,name:“theme_a”)。 它有(许多)function[(id:1,name:“feature_a”),(id:2,name:“feature_b”),(id:3,name:“feature_c”)] 查询应该像这样工作:Theme.the_query(:features => {:id => [1,2]}),结果是主题,但是当我以这种方式放置ID时Theme.the_query(:features => {:id => [2,4]})结果应为零。 我已经构建了Theme.joins(:features).where(:features => {:id => features_array_ids})但它返回了所有具有features_array_ids元素的主题。 如果features_array_ids = [2,4]它返回主题,但我不希望这样。 对于语法错误我很抱歉,我希望你知道我的意思。 编辑: 找到解决方案 Theme.select(“*”).from(“themes”).joins(“INNER JOIN theme_features ON themes.id = theme_features.id”).where(“EXISTS(SELECT theme_id FROM theme_features tf WHERE tf.feature_id IN (#{features_array_ids.join(“, “)}) AND tf.theme_id = themes.id GROUP BY tf.theme_id HAVING COUNT(*) = #{features_array_ids.count})”)

RAILS有GROUP BY … WITH ROLLUP查询吗?

GROUP BY …使用ROLLUP是sql中的一个很酷的function。 Rails是否支持ROLLUP? 我该怎么写这样的查询, .group(‘column1, column2,….’)

ActiveRecord where.not不工作/奇怪的行为

用户has_many计划。 我正在尝试查找没有状态为“已取消”的所有用户的ID。 很想知道下面的行为是什么。 对于上下文,应该返回的是: User.select { |u| u.plans.select { |p| p.status != “canceled” }.count > 0 }.map(&:id) # => [27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63] 这是我得到的: # statement 1 […]

SQL查询顺序问题

所以我在activerecord中有以下模型,我将使用Discussion.user_replied_group_discussions(@user)它返回最近回复的讨论好,但是如何修改私有方法以按最新回复时间订购返回的讨论? # Table name: discussions # # id :integer not null, primary key # title :string(255) not null # content :text(255) not null # created_at :datetime # updated_at :datetime # user_id :integer # discussable_id :integer # discussable_type :string(255) class Discussion :commentable, :dependent => :destroy # #this is the scope that I am having trouble with: […]