This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes SQL Count Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "SQL Count " Watch "SQL Count " New topic
Author

SQL Count

Stephen ODonnell
Greenhorn

Joined: Sep 07, 2004
Posts: 19
Hi all,

I have a table which contains a list of different error codes. I want to do a count of each different error code i.e code 3000 = 3, code 4000 = 10, etc but can't figure it out (I'm new to sql)
I've tried a few different sql statements, such as:

which will print out the number of different codes.

Any help greatly appreciated,
Thanks,
Stephen.
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1744
    
    2


Read up on how count() and group by work. (Some versions of SQL may allow you to omit the group by section in this particular query, but most versions require it.)

My proposed query is based on some assumptions about what you trying to do. Correct me if I'm wrong.

I have a table which contains a list of different error codes

A setup table listing all possible valid error codes or error codes representing errors that were actually recorded? I assumed the latter.

3000 = 3, code 4000 = 10

So error code 3000 has been recorded 3 times; error code 4000, 10 times; right? Right off the bat this suggests that you want to have two columns in your results, along the lines of

error_code how many times
---------- --------------
30003
400010
523417
etc.

but you have only 1 item, COUNT(DISTINCT Message_code), in your select list, so you know your original query can't be right.

In SQL speak, you essentially want to make a group for each value of message_code (that's what the group by message_code does) and count the number of rows that occurs for each value of the grouped by field (that's what the count(*) does).
Stephen ODonnell
Greenhorn

Joined: Sep 07, 2004
Posts: 19
Hi Michael,

Thanks for your quick reply, thats a great help.

Cheers,
Stephen.
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1744
    
    2
No problem. But was it what you wanted?
 
wood burning stoves
 
subject: SQL Count
 
Similar Threads
COUNT/LIST the number of tables in ACCESS
how to write this query... count, unique, ??
Error occured while initialising for loop:
How to get row-count out from the ResultSet?
Result Set problems