Sql query to create a calculated field

做~自己de王妃 提交于 2019-11-29 11:05:18

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' 

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'

Try this:

SELECT CardNo, UserName, SUM(DATEDIFF('h',DateTime,(SELECT MIN(Datetime) 
                                                    FROM table as t2 
                                                    WHERE t1.CardNo=t2.CardNo
                                                        AND t2.Addr like '%Exit' 
                                                        AND t2.DateTime > t1.DateTime )))
FROM table as t1
WHERE Addr like '%In'
GROUP BY CardNo, UserName
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!