Tomek Wejchorowski Tomek Wejchorowski - 1 year ago 77
SQL Question

Transform SQL query to ActiveRecord Query

I don't know how to convert this PostgreSQL query:

select news_id, sum(case when then 1 else -1 end) as max_positive from likes group by(news_id) order by(max_positive) desc

to ActiveRecord Query.

What I tried:
.sum('CASE WHEN THEN 1 ELSE -1 end')
.max_by { |_k, v| v }

But result is array and not select news_id.

Answer Source

Like this?"news_id, SUM(case when then 1 else -1 end) as max_positive").order("max_positive desc")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download