Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite count, group and order by count

I have a table that looks like this:

FOO  BAR  BAZ ----+----+---- foo1 bar1 baz1 foo2 bar3 baz2 foo3 bar1 baz3 foo4 bar1 baz4 foo5 bar3 baz5 foo6 bar1 baz6 foo7 bar2 baz7 

And as a result I would like to get the count of how many times each bar appeared in the table.. so, the output I'm looking for looks like this:

BAR   COUNT -----+----- bar1    4 bar3    2 bar2    1 

Can I do a query for something like this in SQLite? I guess it should be pretty easy, but I am not an SQL programmer by any means, and I just need this simple query as a part of a python script.. Thank you.

like image 859
tkit Avatar asked Jul 19 '11 09:07

tkit


People also ask

How do you ORDER BY count in SQL?

Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.

Can we use count in ORDER BY?

For uninitiated, a COUNT() function is used to find the total number of records in the result set. It is usually used in combination with the GROUP BY clause to prepare a summary of the total number of records in each group. It can further be used with ORDER BY clause to sort the obtained summary table.

How do you use count in GROUP BY clause?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

Can count be used with GROUP BY?

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


1 Answers

SELECT foo, count(bar) FROM mytable GROUP BY bar ORDER BY count(bar) DESC; 

The group by statement tells aggregate functions to group the result set by a column. In this case "group by bar" says count the number of fields in the bar column, grouped by the different "types" of bar.

A better explanation is here: http://www.w3schools.com/sql/sql_groupby.asp

like image 125
Edgar Velasquez Lim Avatar answered Sep 23 '22 22:09

Edgar Velasquez Lim