If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Query help (Sum function)

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-09-04, 19:31
barkerj barkerj is offline
Registered User
 
Join Date: Nov 2004
Posts: 1
Query help (Sum function)

Hi,

I have two tables as below.

TableA:
ID (Primary Key)
Location
Date

TableB:
ID (Primary Key)
Qty

What I am trying to do is to return a result set with the first column displaying all locations with a particular date value with the second column displaying the sum of all TableB's Qty values for that location and date.

Thus, for each line of the resultset, if there are 2 records in TableA for a particular location and date. I want to go to TableB and sum the Qty values for the corresponding IDs in that table.

Is it possible to do this using one SQL statement?
Reply With Quote
  #2 (permalink)  
Old 11-10-04, 05:39
Sudar Sudar is offline
Registered User
 
Join Date: Jul 2004
Location: Mars
Posts: 137
Thumbs up try this

hai...

Try the following code

select ta.location, sum(qty) from ta , tb where ta.id = tb.id and ta.date = 'date_condition' group by ta.location;

and replace the date_condition with ur own date condition..

Do let me know whether this helped you...
__________________
Sudar

--
My Blog
Reply With Quote
  #3 (permalink)  
Old 11-10-04, 06:33
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
if all TableA locations are to be returned, including those with no matching rows in TableB, then it requires a LEFT OUTER JOIN
Code:
select a.Location
     , coalesce(sum(b.Qty),0) as Qty 
  from TableA as a
left outer
  join TableB as b
    on a.ID = b.ID 
 where a.`Date` = 'date value' 
group 
    by a.Location
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
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

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On