Select lower case column with group by or select lower(column) in Rails 4

北城余情 提交于 2020-01-24 12:34:53

问题


How to achieve following in rails 4?

Here is my PostgreSQL query and works correctly

SELECT lower(name) as c_name, count(*) as cc FROM categories  GROUP BY c_name  ORDER BY cc desc LIMIT 3

Ii gives me following results

 "ecommerce solutions";6
 "vmware";6
 "big data analytics";5

But when I write same query in Rails 4 as

Category.select("lower(name) as c_name, count(*) as cc").group("c_name").order("cc desc").limit(3) 

Above query generates following query which is same as above PostgreSQL query

SELECT lower(name) as c_name, count(*) as cc FROM "categories"  GROUP BY c_name  ORDER BY cc desc LIMIT 3

gives following results

[#<Category id: nil>, #<Category id: nil>, #<Category id: nil>]

Why this is happening ? when I cut my query to

 Category.select("lower(name)").limit(3)

This also does not work, and results into

 [#<Category id: nil>, #<Category id: nil>, #<Category id: nil>]

I want to do group on lower(name) with count as aggregation, I have many variances of name in Category model

Ex. data set

"Vmware" and "VMware" and "VMWARE" and "vmware" 

How can I group on lower(name) in Rails 4?

In simple words, How to write equivalent query of following in Rails 4?

SELECT lower(name) as c_name, count(*) as cc FROM categories  GROUP BY c_name  ORDER BY cc desc LIMIT 3

回答1:


The result is correct, but Rails displays it wrong. Just access results manually:

results = Category.select("lower(name) as c_name, count(*) as cc").group("c_name").order("cc desc").limit(3) 
results.first['c_name']


来源:https://stackoverflow.com/questions/30216266/select-lower-case-column-with-group-by-or-select-lowercolumn-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!