Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all columns by a unique column value in Rails 3

In Rails 3, how do i select rows based on unique column values, i need to get all the columns for eg:

SELECT COUNT(DISTINCT date) FROM records

This only returns date column, but i want all the columns (name, date , age , created_at) columns not just the date.

Thanks for your help

like image 447
Anand Kumar Avatar asked Dec 04 '22 04:12

Anand Kumar


2 Answers

The issue here is that, by definition, there may be multiple records with the same date. It requires logic in the user space to determine which of the multiple records with the unique date to use. Here's some code to get those rows:

Record.select("distinct date").each do |record|
    records = Record.find_by_date record.date
    puts records.count # do something with the records
end

If what you're really after is uniqueness among multiple columns, list all the relevant columns in the distinct query:

Record.select("distinct date, name, age, created_at").each do |record|
    puts record.date
    puts record.name
    puts record.age
    puts record.created_at
    # ``record'' still represents multiple possible records
end

The fact that you are using distinct means that each "row" returned actually represents n rows, so the DB doesn't know which of the n rows to pull the remaining columns from. That's why it only returns the columns used in distinct. It can do no other...

like image 62
Troy Avatar answered Dec 26 '22 03:12

Troy


I think this will help you

Model.find(:all, :select => 'DISTINCT name, date, age, created_at')

Please use it and let me know.

like image 44
urjit on rails Avatar answered Dec 26 '22 03:12

urjit on rails