Hani Honey
Hani Honey

Reputation: 2131

SQL Subquery - Inexperienced!

I have a database, and I'm trying to show the count of users for each different entry in the "source" field. So for example, show how many people share the same source. Would I have to do this through a subquery? Or do I have to actually know what the titles of the sources are in the database?

Upvotes: 0

Views: 84

Answers (5)

MAXE
MAXE

Reputation: 5122

This counts the record grouped by the values of myField:

SELECT COUNT(1) As rCount FROM myTable GROUP BY myField

You can also group your query with multiple GROUP clauses. This will give you the counting of any sub-grouping:

SELECT myField1, myField2, COUNT(1) As rCount FROM myTable GROUP BY myField1, myField2

The COUNT(1) is better than COUNT(*), for the Sql engine.

Upvotes: 0

Neil N
Neil N

Reputation: 25258

You are looking for GROUP BY query.

Start here: http://www.sql-tutorial.com/sql-group-by-sql-tutorial/

Upvotes: 0

Dolan Antenucci
Dolan Antenucci

Reputation: 15942

You can use GROUP BY:

SELECT COUNT(*), source FROM mytable GROUP BY source;

Upvotes: 1

ShaneBlake
ShaneBlake

Reputation: 11096

SELECT Source, count(Source) as TotalPeople
FROM SomeTable
GROUP BY Source

Upvotes: 0

troelskn
troelskn

Reputation: 117517

Sounds like you'd use grouping:

select source, count(*) from users group by source ;

Upvotes: 1

Related Questions