user1758446
user1758446

Reputation: 3

Display Employee Name, Dept Name, Salary, Grade, Experience (EX: XX Years YY Months ZZ Days) for all the employees in SQL

please help in the following query Display Employee Name, Dept Name, Salary, Grade, Experience (EX: XX Years YY Months ZZ Days) for all the employees

ENAME     DNAME    SAL  GRADE      EXPERIENCE

SCOTT    RESEARCH  3000   4        12 Years 3 months 15 days

like this i need to get the output.

i have tried to write upto years but months,days i am not able to get.

select distinct ename,dname,sal,grade,
 (round((months_between(sysdate,hiredate)/12))||' years' EXP 
 from emp,salgrade,dept 
 where dept.deptno=emp.deptno and sal between losal and highsal;

Upvotes: 0

Views: 1714

Answers (3)

user3095423
user3095423

Reputation: 31

Here is your required answer in ORACLE SQL

select (floor(months_between(sysdate,hiredate)/12)) YEARS,
round(((months_between(sysdate,hiredate)/12)-(round(months_between(sysdate,hiredate)/12)))*12) months
from abc;

Upvotes: 0

JohnLBevan
JohnLBevan

Reputation: 24430

Here's a T-SQL (SQL Server) solution which I've got working (based on tests so far). Sadly I don't have an oracle instance to play on, but hopefully this shouldn't be too hard to convert:

declare @fromDate date = '2010-11-21'
, @toDate date = getutcdate()

--from date must be before to date
declare @tempDate date
if @toDate < @fromDate 
begin
    set @tempDate = @toDate
    set @toDate = @fromDate
    set @fromDate = @tempDate
end

declare @fDD int = datepart(dd,@fromdate)
, @tDD int = datepart(dd,@todate)
, @fMM int = datepart(mm,@fromdate)
, @tMM int = datepart(mm,@todate)
, @fYYYY int = datepart(yyyy,@fromdate)
, @tYYYY int = datepart(yyyy,@todate)
, @y int, @m int, @d int

--calc difference in years
set @y = @tYYYY-@fyyyy
if @fMM > @tMM or (@fMM=@tMM and @fDD > @tDD)
begin
    set @y = @y - 1
    set @fYYYY = @fYYYY + @y
    set @tempDate = DATEADD(year,@y,@fromDate)
end

--calc remaining difference in months
set @m = DATEDIFF(month,@tempDate,@toDate)
if @tDD < @fDD 
begin
    set @m = @m-1
    set @tempDate = DATEADD(month,@m,@tempDate)
end

--calc remaining difference in days
set @d = DATEDIFF(day,@tempDate,@toDate)

--display results in user friendly and grammatically correct way
select cast(@y as nvarchar(3)) + N' year' + case when @y = 1 then N'' else N's' end + N' '
+ cast(@m as nvarchar(2)) + N' month' + case when @m = 1 then N'' else N's' end + N' '
+  cast(@d as nvarchar(3)) + N' day' + case when @d = 1 then N'' else N's' end + N' '

Upvotes: 0

Suraj Bajaj
Suraj Bajaj

Reputation: 6640

You have got the years.

Use MONTHS_BETWEEN(date1, date2) to get months. Then subtract (year * 12).

Use DAYS_BETWEEN(date1, date2) to get number of days.

See this for more details

Upvotes: 1

Related Questions