David Brierton
David Brierton

Reputation: 7397

SQL Server : convert seconds into hours

I am using SQL Server and joining about 10 tables together using either inner join or left outer join.

I have a column in my select vp_timesheetpunch.TIMEINSECONDS (Time in seconds) that is in seconds and I want to add another column after saying how many hours that is. So that it list both seconds and hours.

select
    vp_timesheetpunch.personnum [Assoc ID],
    vp_timesheetpunch.personfullname [Assoc Name],
    vp_timesheetpunch.laborlevelname4 [Department],
    vp_timesheetpunch.eventdate [Shift Date],
    shiftassignmnt.shiftstartdate [Scheduled Start],
    vp_timesheetpunch.startdtm [Rounded Start],
    vp_timesheetpunch.inpunchdtm [Actual Start],
    vp_timesheetpunch.enddtm [Rounded End],
    vp_timesheetpunch.outpunchdtm [Actual End],
    vp_timesheetpunch.TIMEINSECONDS [Time in seconds]
from
    vp_timesheetpunch
left outer join
    vp_punchexceptions on vp_timesheetpunch.timesheetitemid = vp_punchexceptions.timesheetitemid
inner join
    timesheetitem on vp_timesheetpunch.timesheetitemid = timesheetitem.timesheetitemid
inner join
    workedshift on timesheetitem.workedshiftid = workedshift.workedshiftid
inner join
    shfasgnwshfmm on workedshift.workedshiftid = shfasgnwshfmm.workedshiftid
inner join
    shiftassignmnt on shfasgnwshfmm.shiftassignid = shiftassignmnt.shiftassignid
where
    --limit rows to the specified pay period
    vp_timesheetpunch.eventdate = '1/22/2019'
    --exclude rows that are missing data
    and vp_timesheetpunch.inpunchdtm is not null
    and vp_timesheetpunch.outpunchdtm is not null
    --limit rows to shifts with exceptions
order by
    vp_timesheetpunch.personnum,
    vp_timesheetpunch.eventdate

Is this possible to do on the fly?

I tried adding convert and naming AS Timeinhours but I cannot get the convert to work right.

Data lists time in seconds like "27900"

Upvotes: 0

Views: 998

Answers (1)

Sean Lange
Sean Lange

Reputation: 33581

You need to divide by 3600 but you need to be careful to avoid integer division. Just add .0 to your divisor.

declare @Seconds int = 27900

select [hours] =  convert(decimal(7,2), @Seconds / 3600.0)

Upvotes: 4

Related Questions