dbTalk Databases Forums  

Need help - select the number of rows for each unique value in specified field

mailing.database.sql-general mailing.database.sql-general


Discuss Need help - select the number of rows for each unique value in specified field in the mailing.database.sql-general forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Kevin Blount
 
Posts: n/a

Default Need help - select the number of rows for each unique value in specified field - 09-30-2005 , 04:34 PM






Topics sounds confusing, right? Welcome to my world!

Here's an example. I have a database of phone numbers, such as this:

table: members
field: phone_number

values:
123-456-xxxx
123-234-xxxx
324-667-xxxx
555-767-xxxx
555-876-xxxx
661-661-xxxx
555-555-xxxx
324-324-xxxx

I need to know how many unique area codes there are, and how many
instances of that areas code

e.g.
123 (2)
324 (2)
767 (3)
661 (1)

How, in an SQL SELECT statement, can I do that? I'm not new to SQL, but
this one has me baffled!


Reply With Quote
  #2  
Old   
undercups
 
Posts: n/a

Default Re: Need help - select the number of rows for each unique value in specified field - 10-01-2005 , 11:35 AM






Kevin

Here is the answer (SQL Server 2000) but should work on other RDBMSs

SELECT SUBSTRING(phone_number,1,3)
FROM members

I have assumed that your require the first characters in all cases.

Hope this helps


Duncan


Reply With Quote
  #3  
Old   
undercups
 
Posts: n/a

Default Re: Need help - select the number of rows for each unique value in specified field - 10-01-2005 , 11:38 AM



Opps forgot to add the count

SELECT SUBSTRING(phone_number,1,3), COUNT(*)
FROM members
GROUP BY SUBSTRING(phone_number,1,3)


Reply With Quote
  #4  
Old   
Kevin Blount
 
Posts: n/a

Default Re: Need help - select the number of rows for each unique value in specified field - 10-03-2005 , 08:18 AM



Many thanks, undercups. I had to use SUBSTR rather than SUBSTRING, but
the rest worked perfectly.


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.