I want to find out the number of elements which appears only once in a table.
in sql
select count() from (SELECT count(),id FROM trans GROUP BY id HAVING count(*)=1) temptable
How can this be done in rails active record?
there are mill开发者_如何学编程ions of records in the table.
what exectly you want ... ??? sorry but i didn't understand your requirement....
what you have done is good and right one (only one modification is there count(*))...
although you can remove select * from your query...
simply you can write
SELECT count(*),id FROM trans GROUP BY id HAVING count(*)=1
it will also give the same result with more performance
-- edit / update
as you want to know about the count of this result then you can apply count(*) on this query
as -
SELECT count(*) from ( select id FROM trans GROUP BY id HAVING count(*)=1)
This should work:
Trans.find(:all, :select => 'COUNT(*)', :group => 'trans.id HAVING COUNT(*) = 1')
Try
find_by_sql("SELECT count(*) from ( select id FROM trans GROUP BY id HAVING count(*)=1)")
精彩评论