Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

sorting - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...