Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

database - Sql query to create a calculated field

I have a database table like this:
enter image description here
I hope I can explain this well, so you can understand.

I want to calculate how many hours each employee has worked.
For example for "Arjeta Domi" we have Cell(2,3) - Cell(3,3) + Cell(4,3) + Cell(5,3), making the difference of each logOut time with Login time.

enter image description here

The final table that I want will have these columns: CardNo, UserName, Date, PauseTime, WorkTime

I tried this query: taken from the duplicate

SELECT DISTINCT
  [Card NO], 
  [User Name],  
  (
    SELECT
      MIN(DateTime) AS [Enter Time], 
      MAX(DateTime) AS [Exit Time], 
      MAX(DateTime) - MIN(DateTime) AS [Inside Hours] 
    FROM
      ExcelData
  ) 
FROM
  ExcelData
GROUP BY
  [Card NO], [User Name], DateTime

The DateTime Column is of type String, not DateTime. I am working with MS Access Database.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Select all rows with 'm001-1-In' with DateTime as I and add the fitting 'm001-1-Exit' rows to this with a Subquery as O, this will look like this:

SELECT t1.[Card No], t1.[User Name],dateTime as I
,(Select TOP 1 dateTime from Tab t2 where  t2.[Card No]= t1.[Card No] 
and  t2.[User Name]= t1.[User Name] and  t2.Addr='m001-1-Exit' 
and t2.DateTime>t1.datetime ORDER by DateTime) as O
FROM Tab t1
where t1.Addr='m001-1-In' 

enter image description here

Now it's easy to encapsulate this, show as Prepared below and add our SUM and Grouping to this:

SELECT [Prepared].[Card No], [Prepared].[User Name], SUM(DateDiff('n',I,O))/60 AS Hours
FROM (
      SELECT t1.[Card No], t1.[User Name],dateTime as I
    ,(Select TOP 1 dateTime from Tab t2 where  t2.[Card No]= t1.[Card No] 
      and  t2.[User Name]= t1.[User Name] and  t2.Addr='m001-1-Exit' 
      and t2.DateTime>t1.datetime ORDER by DateTime) as O
FROM Tab t1
where t1.Addr='m001-1-In' 
)  AS [Prepared]
GROUP BY [Prepared].[Card No], [Prepared].[User Name]

If you need to restrict the DateRange you add the needed conditions to the row where t1.Addr='m001-1-In'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...