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 > DB2 > question on sum function

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-13-04, 10:15
rick_cold rick_cold is offline
Registered User
 
Join Date: Jul 2003
Posts: 16
question on sum function

hello, guys:


I have a question about sum function using DB2. I am using DB2 Universal Database Version 7.2 (persona; edition) on Win 2000.

If I have 2 tables:

create table person{
person_id char(10) not null,
.....
primary key(person_id)
};

create table job{
job_id char(20) not null,
start_date TIMESTAMP;
stop_date TIMESTAMP;
person_id char(10),
primary key(job_id)
};

You can see from the above 2 tables, job table has a foreign key pointing
to person table. A person may have multiple jobs.

What I try to do is to calculate a person's total working hours for all of his jobs:

SELECT DISTINCT p.id, sum(j.stop_date - j.start_date) from person as p, job as j where p.person_id = j.person_id

From the above sql statement, it seems the result of summation is a BigDecimal, after I turn it into long and divide it by 60 * 60 * 1000 (an hour has that much milliseconds, right?), I got wrong hours.

Could anyone point out my mistakes?

regards,
Reply With Quote
  #2 (permalink)  
Old 08-13-04, 11:08
fadace fadace is offline
Registered User
 
Join Date: Nov 2002
Location: Switzerland
Posts: 523
Cast your sum to numeric before executing the calculation
__________________
F. Celaia
DBA Sybase/DB2/Oracle/MS-SQL
Reply With Quote
  #3 (permalink)  
Old 08-13-04, 11:31
n_i n_i is offline
:-)
 
Join Date: Jun 2003
Location: Toronto, Canada
Posts: 4,449
Quote:
Originally Posted by rick_cold
SELECT DISTINCT p.id, sum(j.stop_date - j.start_date) from person as p, job as j where p.person_id = j.person_id
I don't think your approach with using DISTINCT is correct. What you really need is to group results by person and then add up hours within each group, like this:
Code:
select p.person_id, sum(hour(j.stop_date - j.start_date)) from person p, job j where p.person_id = j.person_id group by p.person_id
Reply With Quote
  #4 (permalink)  
Old 08-13-04, 16:02
rick_cold rick_cold is offline
Registered User
 
Join Date: Jul 2003
Posts: 16
thanks,

hour function makes this thing work.

regards,
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