Haris Bašić
Haris Bašić

Reputation: 1383

Select distinct values from a table and add 'count' column

Generally, our application for statistics records searches by IP. That means - three IPs and one query, 3 entries in a database.

We need to show statistic of those searches, but imagine that we have:

query | count | ip

where    2     127.0.0.1
where    1     127.0.0.2
where    4     127.0.0.3
who      4     127.0.2.1

I need, in my rails application, to sort these 'where' as one query. So, if I write Search.order('count DESC'), I need to get results like

query | count
where     7
who       4

Does anyone have solution?

Upvotes: 0

Views: 86

Answers (2)

swiftcode
swiftcode

Reputation: 195

Select query, sum(count) as SumCount from table group by query

Upvotes: 3

Dan Bracuk
Dan Bracuk

Reputation: 20794

Something like this will get you started

select query, sum(count) thecount
from etc

Upvotes: 2

Related Questions