简体   繁体   中英

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'.

could be you need case (not where)

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

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;

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