Unix Technical Forum

Doing Several Math Operations During A SELECT?

This is a discussion on Doing Several Math Operations During A SELECT? within the MySQL forums, part of the Database Server Software category; --> Hi there I have a table like so: cID | jID | Unit | Rate | ------------------------- 1 1 ...


Go Back   Unix Technical Forum > Database Server Software > MySQL

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 02-28-2008, 07:35 AM
Good Man
 
Posts: n/a
Default Doing Several Math Operations During A SELECT?

Hi there

I have a table like so:

cID | jID | Unit | Rate |
-------------------------
1 1 5 250
2 1 4 220
3 2 5 160
4 3 3.5 190
5 4 4 250
6 4 5 250


What I ultimately want to do is get a total cost (Unit * Rate) for each
jID.

So, the total cost for jID 1 would be (5 * 250) + (4 * 220) = 2130; the
total cost for jID 2 would be (5 * 160) = 800; jID 3 would be (3.5 * 190)
= 665; and jID 4 would be (4 * 250) + (5 * 250) = 2250.

Can I get these total amounts via one query? ie: achieve a result like:
jID | Total
-----------
1 | 2130
2 | 800
3 | 665
4 | 2250

Right now I'm just pulling *all* the rows and using PHP to calculate
totals costs, but I was wondering if I could do it at the MySQL level?
Obviously I would never know how many rows share the same jID...

Can someone please take a moment to tell me if my goals are possible
using a single query to give me my results? And if so, what might the
SELECT query be?

Thanks in advance.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 02-28-2008, 07:35 AM
Good Man
 
Posts: n/a
Default Re: Doing Several Math Operations During A SELECT?

Good Man <heyho@letsgo.com> wrote in
news:Xns97A2964EF5A98sonicyouth@216.196.97.131:

> Can I get these total amounts via one query? ie: achieve a result
> like: jID | Total
> -----------
> 1 | 2130
> 2 | 800
> 3 | 665
> 4 | 2250


i worked it out, here's how to do it (i think):

SELECT jID,SUM(Rate * Unit) as Total FROM JobCosts GROUP BY jID ORDER BY
jID

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
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
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 07:02 PM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0
www.UnixAdminTalk.com