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 > COUNT and SUM in the same query?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-11-09, 09:46
Spudhead Spudhead is offline
Registered User
 
Join Date: Jan 2002
Posts: 189
COUNT and SUM in the same query?

Not sure if, or how, I can do this.

My PHP application manages the sending of Greetings from one User to another. I want a query that will tell me how many Greetings were sent to a given User, and what their total value was.

It gets a little tricky.

A Greeting itself does not have value. A Greeting may have a Gift tied to it; a Gift has a fixed value. On top of that: a Greeting does have a "donationAmount" field; if it has a Gift, there may be an amount in there, that should be added to the value of the Gift that is attached to it.

To summarise:

Code:
tblGreetings
	idGreeting (PK)
	idRecipent (FK to tblUsers)
	idGift (FK to tblGifts)
	donationAmount (DOUBLE)

tblGifts
	idGifts (PK)
	giftValue (DOUBLE)
I want a single recordset that returns a count of all the Greetings sent to tblGreetings.idRecipent, and a sum of tblGifts.giftValue and tblGreetings.donationAmount for all those Greetings.
Reply With Quote
  #2 (permalink)  
Old 05-11-09, 10:16
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
Code:
SELECT tblGreetings.idRecipent
     , COUNT(*) AS count_Greetings
     , SUM(tblGifts.giftValue) AS total_giftValue
     , SUM(tblGreetings.donationAmount) AS total_Donations
  FROM tblGreetings
LEFT OUTER
  JOIN tblGifts
    ON tblGifts.idGifts = tblGreetings.idGift
GROUP
    BY tblGreetings.idRecipent
__________________
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