473,408 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

SUM and COUNT Questions: Grovel Grovel

Hi all

Well, I didn't want to have to bring this question to someone else to
answer, but I am truly flummoxed and could use some help. It all boils
down to trying to find the number of jobs available in a particular
state. I have two tables, one called STATES and one called WORK. Here
are excerpts from both:

STATES table:
StateID | StateName | StateAbbr
---------------------------------
1 Alabama AL
2 Alaska AK
44 Texas TX
etc....
WORK table:
WorkID | JobState | JobType
----------------------------
1 2 fireman
2 1 fireman
3 44 fireman
4 44 doctor

(so, job number 1 is located in alaska, job #2 is located in alabama, and
jobs number 3 & 4 are located in Texas)
Now, the original task was to come up with a count/listing of available
jobs in states that have work available:

"SELECT States.StateAbbr, COUNT(*) AS NumJobs FROM States RIGHT JOIN Work
ON States.StateID=Work.JobState GROUP BY Work.JobState ORDER BY
StateAbbr"

This gave me a result something like:

StateAbbr | NumJobs
----------------------
AL 1
AK 1
TX 2

(one 'work' entry for alabama and alaska, and two seperate entries for
work in texas)
NOW.... this all works fine, obviously, but it was designed under the
assumption that there would only be one job per entry in the WORK table.
However, now we'd like to specify number of jobs available for the
particular job type in the WORK table.... i added a column called
"JobsAvail" and now we have an example like:

WorkID | JobState | JobType | JobsAvail
----------------------------------------
1 2 fireman 1
2 1 fireman 1
3 2 police 4
4 44 fireman 1
5 44 doctor 2

So, according to this table, there are now 5 jobs available in alaska, 3
in texas and 1 in alabama. However, if I modify my SELECT statement to
something like:

"SELECT States.StateAbbr, SUM(Work.JobsAvail) AS NumResults FROM States
RIGHT JOIN Work ON States.StateID=Work.JobState GROUP BY Work.JobState
ORDER BY StateAbbr"

I still get the same results as earlier; NumJobs for alaska gives me '1'
instead of the '5' i was expecting, and NumJobs for texas gives me '2'
instead of the '3' i was expecting.

So, it all boils down to this question:

** How can I design my query to return the following result: **

StateAbbr | NumJobs
----------------------
AL 1
AK 5
TX 3
Thanks for reading, LONG bloody question I know, but like I said, I'm
just running circles around this and truly need some help...

Thanks!!! Oh, MySQL 4.1 on Linux

- GM

Jul 23 '05 #1
6 1794
Good Man wrote:
"SELECT States.StateAbbr, SUM(Work.JobsAvail) AS NumResults FROM States
RIGHT JOIN Work ON States.StateID=Work.JobState GROUP BY Work.JobState
ORDER BY StateAbbr"

I still get the same results as earlier; NumJobs for alaska gives me '1'
instead of the '5' i was expecting, and NumJobs for texas gives me '2'
instead of the '3' i was expecting.


I tried the example exactly as you gave it and it does seem to give the
desired output. Below I include the database dump of what I typed in,
with the query that gave the desired output. Try the query in the mysql
CLI and see if you get the desired results.

If so, is your query in a web app that isn't deploying correctly or
something? Try outputting some debugging-type harmless static string in
the web app and see if you can get that type of change to deploy.

Regards,
Bill K.

CREATE DATABASE `test`;
USE `test`;

DROP TABLE IF EXISTS `states`;
CREATE TABLE `states` (
`stateid` int(11) default NULL,
`statename` varchar(30) default NULL,
`stateabbr` varchar(20) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `states` (`stateid`,`statename`,`stateabbr`) VALUES
(1,'Alabama','AL'),
(2,'Alaska','AK'),
(44,'Texax','TX');

DROP TABLE IF EXISTS `work`;
CREATE TABLE `work` (
`workid` int(11) default NULL,
`jobstate` varchar(20) default NULL,
`jobtype` varchar(30) default NULL,
`jobsavail` int(11) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `work` (`workid`,`jobstate`,`jobtype`,`jobsavail`) VALUES
(1,'2','fireman',1),
(2,'1','fireman',1),
(3,'2','police',4),
(4,'44','fireman',1),
(5,'44','doctor',2);

SELECT States.StateAbbr, SUM(Work.JobsAvail) AS NumResults FROM States
RIGHT JOIN Work ON States.StateID=Work.JobState GROUP BY Work.JobState
ORDER BY StateAbbr;
Jul 23 '05 #2
"Good Man" <he***@letsgo.com> wrote in message
news:Xn************************@216.196.97.131...
Hi all

Well, I didn't want to have to bring this question to someone else to
answer, but I am truly flummoxed and could use some help. It all boils
down to trying to find the number of jobs available in a particular
state. I have two tables, one called STATES and one called WORK. Here
are excerpts from both:

STATES table:
StateID | StateName | StateAbbr
---------------------------------
1 Alabama AL
2 Alaska AK
44 Texas TX
etc....
WORK table:
WorkID | JobState | JobType
----------------------------
1 2 fireman
2 1 fireman
3 44 fireman
4 44 doctor

(so, job number 1 is located in alaska, job #2 is located in alabama, and
jobs number 3 & 4 are located in Texas)
Now, the original task was to come up with a count/listing of available
jobs in states that have work available:

"SELECT States.StateAbbr, COUNT(*) AS NumJobs FROM States RIGHT JOIN Work
ON States.StateID=Work.JobState GROUP BY Work.JobState ORDER BY
StateAbbr"

This gave me a result something like:

StateAbbr | NumJobs
----------------------
AL 1
AK 1
TX 2

(one 'work' entry for alabama and alaska, and two seperate entries for
work in texas)
NOW.... this all works fine, obviously, but it was designed under the
assumption that there would only be one job per entry in the WORK table.
However, now we'd like to specify number of jobs available for the
particular job type in the WORK table.... i added a column called
"JobsAvail" and now we have an example like:

WorkID | JobState | JobType | JobsAvail
----------------------------------------
1 2 fireman 1
2 1 fireman 1
3 2 police 4
4 44 fireman 1
5 44 doctor 2

So, according to this table, there are now 5 jobs available in alaska, 3
in texas and 1 in alabama. However, if I modify my SELECT statement to
something like:

"SELECT States.StateAbbr, SUM(Work.JobsAvail) AS NumResults FROM States
RIGHT JOIN Work ON States.StateID=Work.JobState GROUP BY Work.JobState
ORDER BY StateAbbr"

I still get the same results as earlier; NumJobs for alaska gives me '1'
instead of the '5' i was expecting, and NumJobs for texas gives me '2'
instead of the '3' i was expecting.

So, it all boils down to this question:

** How can I design my query to return the following result: **

StateAbbr | NumJobs
----------------------
AL 1
AK 5
TX 3


Some one else will doubtless give you one single query that swallows this
problem whole. I use temporary table to break things up into 2 or more
simpler steps.

# Get the count of jobs available in each state (JobState).
CREATE TEMPORARY TABLE tmp_JobCounts
SELECT JobState,
COUNT(WorkID) As NumJobs
FROM WORK
GROUP BY JobState;

You already knew how to get those counts. Notice that I didn't bother with
the state abreviations (yet!). Note, also, that this is a good candidate
for a temporary table. It's bound to be small. At least it would be a
surprise to me if we returned counts for more than 50 states!

# Replace the State code (JobState) in tmp_JobCounts with the state
abbreviation
# and show the results.
SELECT StateAbbr, NumJobs
FROM tmp_JobCounts
LEFT JOIN STATES
ON (tmp_JobCounts.JobState=STATES.StateID);
ORDER BY StateAbbr;

Our temporary table works just like any ordinary table except that it can go
away when we are done with it. Here we just join STATES to get at the
abreviations. I believe this gives the results you seek.

# Be neat and drop the temporary table
# Not strictly necessary since it will go bye bye automatically
# when the connection is closed.
DROP TABLE tmp_JobCounts;

I just like temporary tables and less complex sql statements. The simpleton
in me tends to lose track (fast!) when I try to accomplish more than 1 or 2
things in a single statement.

Thomas Bartkus

Jul 23 '05 #3
Bill Karwin <bi**@karwin.com> wrote in
news:d7*********@enews4.newsguy.com:
I tried the example exactly as you gave it and it does seem to give
the desired output. Below I include the database dump of what I typed
in, with the query that gave the desired output. Try the query in the
mysql CLI and see if you get the desired results.


Thanks for your help. Would you believe I was just using bad data?

Seriously, open up a paypal account or something, you should be getting
paid for all the advice/troubleshooting/coding you do in this NG. Or, just
bank all that karma :)

Thanks again!!

Jul 23 '05 #4
"Thomas Bartkus" <to*@dtsam.com> wrote in
news:SI********************@telcove.net:
I just like temporary tables and less complex sql statements. The
simpleton in me tends to lose track (fast!) when I try to accomplish
more than 1 or 2 things in a single statement.


Thanks Thomas, I appreciate the time and effort you put into solving my
problem.

On a similar point, I thought the use of 'temporary tables' was something
to avoid? I thought I read that somewhere along the way....

Thanks again.
Jul 23 '05 #5
"Good Man" <he***@letsgo.com> wrote in message
news:Xn************************@216.196.97.131...
"Thomas Bartkus" <to*@dtsam.com> wrote in
news:SI********************@telcove.net:
I just like temporary tables and less complex sql statements. The
simpleton in me tends to lose track (fast!) when I try to accomplish
more than 1 or 2 things in a single statement.


Thanks Thomas, I appreciate the time and effort you put into solving my
problem.

On a similar point, I thought the use of 'temporary tables' was something
to avoid? I thought I read that somewhere along the way....


If you can recall what you read, please pass it along to me. As long the
table you create is small, I don't think there is a downside. I'm not even
sure it's a problem if the tables are large! You can query, modify, and
even index them. They are indistinguishable from ordinary tables other than
the fact that they exist only locally to a particular connection. No one
else can see them. And frequently, that's exactly what the doctor ordered.

I learned, and got into the habit of using, temporary tables from the days
before sub queries were available in MySQL. Now that sub queries are
available, I find I like the temporary table workaround better. I don't
know MySQL internals - but I'd be willing to make a beer bet that MySQL is
using those same temp tables internally every time you call a sub query.

Thomas Bartkus
Jul 23 '05 #6
Good Man wrote:
On a similar point, I thought the use of 'temporary tables' was something
to avoid? I thought I read that somewhere along the way....


Speaking for myself, I think it adds a layer of complexity. For
instance, what if you try to create the temp table and it has already
been created earlier in the life of your app? What if you are using
tranparent connection pooling, and you can't rely on your web app
getting the same db connection on the next request? These issues are
all solvable, but they distract me from the problems I'm trying to solve
with my application.

That said, there are some exotic problems that are truly easier to solve
with temp tables. And someone else commented today that they use temp
tables when using LOAD DATA INFILE; load the data, then validate it or
clean it, then migrate it to your persistent tables. That's a pretty
good use of temp tables.

Regards,
Bill K.
Jul 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Kong Li | last post by:
Follow up to this thread, the latest Oracle 9i release 2 patchset (9.2.0.5) fixed the handle count leak problem. The problem is in Oracle client component. Thanks. Kong ----- From: Kong...
8
by: Invalidlastname | last post by:
Hi, We are developing an asp.net application, and we dynamically created certain literal controls to represent some read-only text for certain editable controls. However, recently we found an issue...
68
by: Martin Joergensen | last post by:
Hi, I have some files which has the following content: 0 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0
0
by: DAnne | last post by:
I'm trying to do a simple count function in xslt and it's turning out to be extremely painful. I have a report that brings back a set of responses for each question per section in an Audit. I...
1
by: cpritcha | last post by:
I an new to access and trying to complete a summer camp evaluation form that counts the number of data that is the same. Let me explain about the table. I have a series of questions like...
8
by: C10B | last post by:
hi, I have a table with several million rows. Each row is simply the date and time a certain page was viewed. eg page1 1-1-00 page2 2-1-00 page1 16-1-00 page1 17-1-00
1
by: carolyns | last post by:
I am working with Access 2000, on Windows XP (all updates). I designed a survey in Word with 150+ questions. Roughly 60 questions use a lookup list of 7 different responses. I have the survey...
0
by: imran haq | last post by:
Hi All, I have 3 rather Long Questions that are causing alot of trouble: I would appreciate all the help i can get and tried to use A post sent to atli in the past but it did not help... !) I...
12
by: petter | last post by:
Hi! I have two questions: one question that regards the COUNT-function, and one about how to display a month even if I don’t have any data for that month. I have an Access database where I want...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.