简体   繁体   中英

Date operation with round giving wrong results (oracle sql on db.grussell.org)

I'm practicing SQL from the execises at db.grussell.org and excecise 10 from tutorial 5 ( https://db.grussell.org/sql/interface.cgi?tn=Tutorial%205&qn=9 ) asks for how old are employees in months.

Here is the question

How old is each employee in months. 
Format this as employee number against age in months. 
Round to the nearest whole number of months.

Here is my code (empno is the employee ID, dob is the date of birth as a date type on the employee table

select e.empno, 
 round( months_between ( trunc(sysdate,'mm'),trunc(dob) ) ) 
  from employee e

Here are my results

EMPLOYEE MONTHS_BETWEEN
1       882
2       845
3       674
4       647
5       705
6       756
7       832
8       714
9       714
10      670
11      658
12      700
13      902
14      853
15      748
16      658
17      683
18      673
19      702
20      640
21      622
22      927
23      751
24      810
25      758
26      689
27      779
28      732
29      586
30      633
31      744
32      695

For the rows where the employee number is 5,10 and 16 the result is incorrect for some reason that I cannot understand, for all the others the result is correct.

I'm suspecting that I'm missing something on the round function or not adding or subtracting some date on the months_between parameters.

Could someone point me in the right direction on what would be wrong with those? I can't really understand why some of the data is correct and some isn't... There is a chance that the exercise is wrong but I would not be able to tell.

The reason is because you are truncating sysdate . So, as of this month (July 2017), you are measuring the age as of July 1st, instead of the current date.

Instead just do:

select e.empno, 
       round(months_between(sysdate, e.dob)) as age_in_months
from employee e;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM