简体   繁体   English

将十进制数转换为年份和月份SQL * Plus

[英]Converting a decimal number to years and months SQL*Plus

I am trying to get an age in years and months from a given DOB. 我试图通过给定的DOB来确定年龄和年龄。 Right now, my code looks like this: 现在,我的代码如下所示:

COLUMN name FORMAT A25
SELECT sNo, fName||CHR(13)||lName Name, sex, TRUNC((CURRENT_DATE - dob) / 365.24, 1) Age
FROM Staff
WHERE position IN ('Manager', 'Secretary')
ORDER BY age DESC;

And it gives me Age outputs in decimal numbers (such as 58.6) which I understand, but I am needing to convert that .6 into a month somehow. 它为我提供了年龄理解的十进制数字(例如58.6),但我需要将.6转换为一个月。

I am thinking that my method of doing this conversion isn't the most efficient, but I have been searching for hours for a solution, but to no avail. 我以为我进行这种转换的方法并不是最有效的,但是我一直在寻找解决方案的几个小时,但无济于事。 I've seen DATEDIFF, but I keep getting an invalid identifier error when trying to use it. 我已经看过DATEDIFF,但尝试使用它时始终收到无效的标识符错误。

Any ideas? 有任何想法吗?

How about something like this: 这样的事情怎么样:

SELECT sNo, fName||CHR(13)||lName Name, sex, 
  TRUNC((CURRENT_DATE - dob) / 365.24, 1) Age,
  TRUNC(MONTHS_BETWEEN(CURRENT_DATE, dob) / 12) YEARS,
  MOD(TRUNC(MONTHS_BETWEEN(CURRENT_DATE, dob)), 12) MONTHS
FROM Staff
WHERE position IN ('Manager', 'Secretary')
ORDER BY age DESC;

And here is the SQL Fiddle . 这是SQL Fiddle

And this should get you the days as well: http://sqlfiddle.com/#!4/f3a57/4 而且这也应该让您度过美好的日子: http//sqlfiddle.com/#!4 / f3a57 / 4

SELECT sNo, fName||CHR(13)||lName Name, sex, 
  TRUNC((CURRENT_DATE - dob) / 365.24, 1) Age,
  TRUNC (MONTHS_BETWEEN (CURRENT_DATE, dob) / 12) YEARS,
  MOD (TRUNC (MONTHS_BETWEEN (CURRENT_DATE, dob)), 12) MONTHS,
  TO_DATE (CURRENT_DATE) - 
      ADD_MONTHS (dob,TRUNC (MONTHS_BETWEEN (CURRENT_DATE, dob))) DAYS
FROM Staff
WHERE position IN ('Manager', 'Secretary')
ORDER BY age DESC;

Good luck. 祝好运。

SELECT sNo, fName||CHR(13)||lName Name, sex, 
 DATEDIFF(year, dob, Current_Date) - 1 + ' years & ' + dbo.FullMonthSeperation(CURRENT_DATE, dob) + ' months.' AS 'Age'
FROM Staff
WHERE position IN ('Manager', 'Secretary')
ORDER BY age DESC;

I borrowed the function from Calculating number of full months between two dates in SQL as you've got to both consider negative and positive values depending on the time of the year... I'm sure there's a better way to do the months also, the year should be optimal. 我从SQL中计算两个日期之间的完整月份数中借用了该函数,因为您必须根据一年中的时间同时考虑负值和正值...我敢肯定,还有更好的方法可以计算月份,年份应该是最佳的。

Hope this works in SQL Plus! 希望这可以在SQL Plus中使用! Same concept though. 虽然相同的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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