Mitchell Fortman
Mitchell Fortman

Reputation: 9

How to create a calculated field with a where clause in the calculation

The image shows the table from this code: select * from PunchClock where punchmonth = 1 and PunchDay = 1 and PunchYear = 2018

I am trying to calculate the number of hours worked per day in a database. Our table for this has 2 columns that pertain to this. InOut is a column that has either 1 or 0 (1 = punch in, 0 = punch out), and then there is the punchdatetime. How could I use these two fields to calculate how many hours are worked per day.

I have tried to subtract the punch time in from the punch time out but that won't work.

select PunchMonth, PunchDay, PunchYear, 
      ((PunchDateTime where InOut = 0) - (punchdatetime where InOut = 1))
  from PunchClock

Error Message: Incorrect syntax near the keyword 'where'.

Upvotes: 0

Views: 112

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133370

could be you need case (not where)

select PunchMonth
  , PunchDay
  , PunchYear
  , case INOut = 0 then PunchDateTime else -PunchDateTime end
from PunchClock

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269973

I think you want a case expression. Also, because a given row has either an InOut value of 0 or 1 but not both, I think you need aggregation.

So, I'm guessing:

select PunchMonth, PunchDay, PunchYear,
       datediff(second, min(case when InOut = 0 then punchdatetime end),
                max(case when InOut = 1 then punchdatetime  end)
               ) as seconds_diff
from PunchClock
group by PunchMonth, PunchDay, PunchYear;

Upvotes: 0

Related Questions