user3754535
user3754535

Reputation: 131

SQL query to Rails ActiveRecord

I have the following SQLite query, which is the ActiveRecord equivalent?

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. 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;

Upvotes: 0

Views: 1045

Answers (1)

Tushar Kulkarni
Tushar Kulkarni

Reputation: 134

Below could be an equivalent ruby query for the given sql query.

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.

Upvotes: 1

Related Questions