У меня есть SQL-запрос в приложении Rails, где я пытаюсь найти разницу во времени между текущим временем и первым временем возникновения, записанным в столбце.
now() - FIRST(product_selections.staged_at) as time_in_inventory
SQL здесь пока не нравится использование FIRST
.
Первоначально в ActiveRecord это работало как:
def time_since_first_use
product_selections.none?
? "N/A"
: Time.now - product_selections.order(staged_at: :asc).first.staged_at
end
Вот основной запрос для справки:
SELECT
warehouses.name as warehouse_name,
products.name as product_name,
SUM(product_selections.use_time) as total_time_staged,
now() - FIRST(product_selections.staged_at) as time_in_inventory,
FROM warehouses
LEFT JOIN rfid_tags
ON warehouses.id = rfid_tags.location_id
AND rfid_tags.location_type = 'Warehouse'
LEFT JOIN products
ON rfid_tags.ancestor_product_id = products.id
LEFT JOIN category_assignments
ON category_assignments.product_id = products.id
LEFT JOIN categories
ON category_assignments.category_id = categories.id
LEFT JOIN product_selections
ON product_selections.product_id = products.id
WHERE
warehouses.id = 1063
AND category_assignments.primary = true
GROUP BY
warehouses.id,
warehouses.name,
categories.id,
categories.name,
products.name,
products.working_value
HAVING COUNT(rfid_tags)>0
ORDER BY
categories.name,
products.name