简体   繁体   English

SQL查询Rails ActiveRecord

[英]SQL query to Rails ActiveRecord

I have the following SQLite query, which is the ActiveRecord equivalent? 我有以下SQLite查询,它等效于ActiveRecord?

My main goal here is to build a clients table with a validation of how many sales of the client are over 29 days of antiquity. 我在这里的主要目标是建立一个客户表,以验证上古天数超过29天的客户销售量。 Any help is appreciated guys. 任何帮助是感激的家伙。

select
    clients.id,
    clients.razon,
    clients.rfc,
    clients.state,
    clients.city,
    count(sales.id) AS "Num sales",
    SUM(
        CASE WHEN (
            (julianday('now') - julianday(sales.created_at) > 29)
        ) THEN 1 ELSE 0 END
    ) AS outdated_sales
from clients
join sales
    where clients.id = sales.client_id
    and sales.sku != ""
GROUP by sales.client_id
ORDER BY sales.created_at asc;

Below could be an equivalent ruby query for the given sql query. 以下可能是给定sql查询的等效ruby查询。

Client.joins(:sales)
  .where("clients.id == sales.client_id AND sales.sku IS NOT IN (?)", ["", nil])
  .select("id, razon, rfc, state, city, count(sales.id) as num_sales")
  .order("sales.created_at")

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM