【问题标题】:How do I reference the same table in rails activerecord style如何在 rails activerecord 样式中引用同一个表
【发布时间】:2017-10-31 06:53:47
【问题描述】:

如何以 Rails 活动记录样式编写此查询?

select distinct listmonth, 
        (select count(1) from listing where listmonth between dateadd(month, -3, l.listmonth) and dateadd(month, -1, l.listmonth)) as cnt
from listing l
group by listmonth
order by listmonth

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    这可能是你的 AR 风格。试一试。

    sub_query = Listing
      .select('count(1)')
      .where('listmonth between dateadd(month, -3, l.listmonth) and dateadd(month, -1, l.listmonth)')
      .as('cnt')
    
    Listmonth
      .select('distinct listmonth')
      .select(sub_query)
      .as('l')
      .group('listmonth')
      .order('listmonth')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2013-01-19
      • 2014-11-04
      • 2019-12-26
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      相关资源
      最近更新 更多