[英]Sql query to create a calculated field
我有一個這樣的數據庫表:
我希望我能很好地解釋這一點,所以你可以理解。
我想計算每個員工工作了多少小時。
例如,對於“Arjeta Domi”,我們有Cell(2,3) - Cell(3,3)+ Cell(4,3)+ Cell(5,3),使每個logOut時間與登錄時間不同。
我想要的最終表將包含以下列: CardNo
, UserName
, Date
, PauseTime
, WorkTime
我嘗試了這個查詢:取自副本
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
DateTime
列的類型為String
,而不是DateTime
。 我正在使用MS Access數據庫。
選擇帶有'm001-1-In'的所有行,將DateTime作為I,並將擬合'm001-1-Exit'行添加到此處,子查詢為O,這將如下所示:
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'
現在很容易封裝它,在下面顯示為Prepared並將SUM和Grouping添加到:
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]
如果您需要限制DateRange,則將所需條件添加到where t1.Addr='m001-1-In'
嘗試這個:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.